jqueryimage-preloader

jQuery check preload of image before change attr src


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?


Solution

  • 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];
        }
    }