Skip to content Skip to sidebar Skip to footer

Jquery: Preload An Image On Request With A Callback Function?

I'm helping out a friend with a website he's developing and we are having trouble with preloading images on request. Basically, when the user clicks on a thumbnail of the product a

Solution 1:

Preloading images can be done using following code:

$('<img/'>,{'src': image_source});

As we can also use the load event on images, we can have an callback when one image is done; To solve the issue to fire a callback after four images is loaded, we would need some kind of counter.

Perhaps following code might work (untested):

var preloadImages = function(image_links, callback) {
  var self = this;
  // assume image_links is an array herevar count = image_links.length;
  $.each( image_links, function(){
    $('<img/>', {
      'src': this, // url'load': function(){
        if( --count == 0 ) {
          callback.apply(self);
        }
      }
    });
  });      
}

Post a Comment for "Jquery: Preload An Image On Request With A Callback Function?"