1

I have coded a quite simple function to change the src of an image:

    var imgsDesktop = ["image1.jpg",
                       "image2.jpg",
                       "image3.jpg",
                       "image4.jpg",
                       "image5.jpg"];
    var imgCurrent = 0;
    function imgSlide() {
        $("#ImgDesktop").attr("src", imgsDesktop[imgCurrent]);
        imgCurrent++;
        if(imgCurrent > imgsDesktop.length) {
            imgCurrent=0;
        }
    }
    setInterval("imgSlide()", 7000);

But I would like to preload the next image before changing the attr src of ImgDesktop.

How to do so? What will happen if preloading image takes more than 7 sec?

London Smith
  • 1,622
  • 2
  • 18
  • 39
  • 1
    What research have you done? Preloading is not hard to search and get results. Basic research is expected before asking questions – charlietfl Jan 23 '17 at 14:19
  • 1
    Since you are referencing local images preloading them won't make any significant difference! Here is a great article on preloading https://perishablepress.com/3-ways-preload-images-css-javascript-ajax/ – acesmndr Jan 23 '17 at 14:22
  • @charlietfl yes, like this one http://stackoverflow.com/questions/476679/preloading-images-with-jquery but will it affect the setInterval? – London Smith Jan 23 '17 at 14:23

1 Answers1

2

You can preload them through a Javascript function:

function preloadImages() {
    var imageList = [
        "image1.jpg",
        "image2.jpg",
        "image2.jpg"
    ];
    for(var i = 0; i < imageList.length; i++ ) 
    {
        var imageObject = new Image();
        imageObject.src = imageList[i];
    }
}