BG Image Preloader in jQuery

I have an array of images

var photos = ["images/bg01.jpg", "images/bg02.jpg", "images/bg03.jpg"];

I navigate this array and make them a background div based on the interval

$("#bgimg" + activeContainer).css({
        "background-image" : "url(" + photos[i] + ")",
        "display" : "block",
        "z-index" : currentZindex
    });

EDIT: I need to preload all three images before I make my setInterval function.

Thanks in advance!

+3
source share
3 answers

Set a variable for the number of images to upload. Decrease the counter every time the image finishes loading, and when the counter reaches zero, start displaying the images.

function photoLoaded() {
    if(!--numPhotosLeft) {
        // start showing images
    }
}

var photos = ["images/bg01.jpg", "images/bg02.jpg", "images/bg03.jpg"];
var numPhotosLeft = photos.length;

for(var i = 0; i < photos.length; ++i) {
    var img = new Image();
    img.onload = photoLoaded;
    img.src = photos[i];
}
+1
source
(function($) {
    var photos = ["images/bg01.jpg", "images/bg02.jpg", "images/bg03.jpg"];

    var i = 0;
    function preloadImage() {

        var image = new Image();

        image.onload = function() {
            $("#bgimg" + activeContainer).css({
                "background-image" : "url(" + photos[i] + ")",
                "display" : "block",
                "z-index" : currentZindex
            });

            i++;
            preloadImage();
        };

        image.src = photos[i];


    };

}(jQuery);

This will...

  • upload image
  • set it to the background of your container.
  • repeat with the following image
+1
source

:

var imgCount = images.length;
var counter = 0;
$.each(images, function(i, n) {
   // load each image
   $("<img />").attr("src", n)
               .load(function() {
                  counter++;
                  if(imgCount == counter) {
                     // all images have loaded
                     // call setInterval
                  }

              });
});
0

Source: https://habr.com/ru/post/1778555/


All Articles