本文介绍了在加载所有图像之前触发图像预加载器回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题:
我正在尝试图像预加载,并找到了我尝试过的 这个很棒的解决方案 我接受了代码并将其包装在一个返回诺言的函数中,但是我注意到在加载所有图像之前,done()
处理程序被调用为 ,我在做什么错呢?
I am trying to do image preloading and found this awesome solution which I have tried to adapt.I took the code and wrapped it in a function which returns a promise, but i noticed that the done()
handler was getting called before all the images were loaded, what am I doing wrong?
代码:
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..");
});
控制台输出:
JSFIDDLE:
https://jsfiddle.net/sajjansarkar/f5k94n2r/
推荐答案
交换这两行
promise.resolve();
console.log("loaded:" + url);
承诺正在解决,这会触发其余的解决链.然后添加日志消息.
The promise is resolving which triggers the rest of the resolve chain. Then the log message is added.
这篇关于在加载所有图像之前触发图像预加载器回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!