Jquery: Preload an image on request with a callbac

2020-04-18 06:22发布

问题:

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 <div> slides down that includes a scrolling carrousel of large images. In total there are about 20MB of images that could be loaded in (if you did them all) so preloading them on the page load would not be an option.

Is there a way that we could call a javascript function that begins to preload about 4 images and then when it's done it has a callback function?

Thanks! P.S. We are using jQuery on the page...

回答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 here
  var count = image_links.length;
  $.each( image_links, function(){
    $('<img/>', {
      'src': this, // url
      'load': function(){
        if( --count == 0 ) {
          callback.apply(self);
        }
      }
    });
  });      
}