Cross-browser solution for a callback when loading multiple images?

随声附和 提交于 2019-11-30 22:13:15

Here's a function that will create several images and call a callback when they are all loaded:

function createImages(srcs, fn) {
   var imgs = [], img;
   var remaining = srcs.length;
   for (var i = 0; i < srcs.length; i++) {
       img = new Image();
       imgs.push(img);
       img.onload = function() {
           --remaining;
           if (remaining == 0) {
               fn(srcs);
           }
       };
       img.src = srcs[i];
   }
   return(imgs);
}

var imgs = createImages(['images/img1.png', 'images/img2.png'], myCallback);

P.S. whenever working with .onload for images, you must set the .onload handler before setting the .src value because the onload handler might fire immediately when setting the .src value if the image is in the cache. If you haven't set the onload handler first, then it may never fire because by the time you set the handler, the image is already loaded. This happens in some browsers. Just always set .onload before .src if you need the onload event.

It's called reference counting. It's the standard technique for running a single callback after n tasks have finished.

var count = 2;
img1.onload = function () {
  count-- === 0 && callback();
}
img2.onload = function () {
  count-- === 0 && callback();
}

function callback() {

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