Jquery: Preload an image on request with a callback function?

对着背影说爱祢 提交于 2019-12-02 14:45:01

问题


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);
        }
      }
    });
  });      
}


来源:https://stackoverflow.com/questions/2936778/jquery-preload-an-image-on-request-with-a-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!