Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background-image preloader using jQuery

I'm working on a site that is very background-image intensive. Since some of the images are large, the aesthetic appeal of the page will inevitably suffer at the initial load, probably for several seconds.

So I'm trying to make a background-image preloader with jQuery and here's where I'm at:

$(document).ready(function(e){
  $('*')
    .each(function(){
        if($(this).css('background-image') != 'none'){

            //so, i can get the path, where do i go from here?
            alert($(this).css('background-image').slice(5, -2));

        }
    });
});

I'm used an array of Image() objects, to load the image using the path pulled from my iterator, but I'm lost on where to go from here.

How can I determine when all of the images in the array have 'loaded', so that I can call a function to fade out a preloader curtain or something?

like image 950
Dan Lugg Avatar asked Dec 10 '10 17:12

Dan Lugg


2 Answers

You should be able to pull off something like this (untested!):

$(document).ready(function(e){

   // get a collection of all elements with a BG image
   var bgImages = $('*').filter(function(){
       return $(this).css('background-image') != 'none');

   // get a collection of new images, assigning the sources from the original collection
   }).map(function() {
       return $("<img />").attr("src", $(this).css('background-image').slice(5, -2));
   });

   var len = bgImages.length;
   var loadCounter = 0;

   // use an onload counter to keep track of which ones have loaded
   bgImages.load(function() {
      loadCounter++;
      if(loadCounter == len) {

         // we have all loaded
         // fade out curtain
      }
   }).each(function() {

      // if we have been pulled up from cache, manually trigger onload
      if (this.complete) $(this).trigger("load");
   });
});
like image 182
karim79 Avatar answered Sep 28 '22 15:09

karim79


Here are a few resources to look at:

  • Image Preloader
  • Preloader with Callback

If you use a DOM element instead of Image you can watch the image onload callback

var path = $(this).css('background-image').slice(5, -2);
var img = document.createElement('img');
img.src = path;
$(img).load(function(){ /* incrament counter for loaded images */})
like image 32
Josiah Ruddell Avatar answered Sep 28 '22 14:09

Josiah Ruddell