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

时光毁灭记忆、已成空白 提交于 2019-12-02 03:42:36

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