图像预加载器在加载所有图像之前激活回调

时间:2016-09-09 17:15:34

标签: javascript jquery

问题:

我正在尝试进行图像预加载,并找到了我试图改编的 this awesome solution 。我拿了代码并将其包装在一个返回承诺的函数中,但我注意到了在加载所有图像之前,done()处理程序被称为,我做错了什么?

代码:

function preload(args) {

  var $defer = $.Deferred();
  var preload = args;
  var promises = [];
  for (var i = 0; i < preload.length; i++) {
    (function(url, promise) {
      var img = new Image();
      img.onload = function() {
        promise.resolve();
        console.log("loaded:" + url);
      };
      console.log("loading:" + url);
      img.src = url;
    })(preload[i], promises[i] = $.Deferred());
  }
  $.when.apply($, promises).done(function() {
    console.log("All images ready sir!");
    $defer.resolve();
  });

  return $defer;
}

var images = ['https://pbs.twimg.com/media/CbM1w65UcAAKfSJ.jpg', 'https://www.kenrockwell.com/nikon/d600/sample-images/600_0985.JPG', 'https://developer.nvidia.com/sites/default/files/akamai/gameworks/blog/GameWorks_Vulkan_and_OpenGL_Samples/vulkan2.png', 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSKJ1fJHxLQ6unFkHZnHJoT-RfqrBvWMrzhmRFAPUt0VvdvZSDd', 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTyvamruO8NCTeQJXtQaXM8xEQS5P9ANh_npfgZpv-7x8ISvzX5zg'];

preload(images).done(function() {
  console.log("OK, begin business process..");

});

控制台输出:

enter image description here

的jsfiddle:

https://jsfiddle.net/sajjansarkar/f5k94n2r/

1 个答案:

答案 0 :(得分:2)

交换这两行

    promise.resolve();
    console.log("loaded:" + url);

承诺正在解决,触发解决方案链的其余部分。然后添加日志消息。