Sajjan Sarkar Sajjan Sarkar - 2 months ago 10
Javascript Question

Image Preloader Callback firing before all images have loaded

Problem:

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?

Code:

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..");

});


Console Output:

enter image description here

JSFIDDLE:

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

Answer

Swap these two lines

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

The promise is resolving which triggers the rest of the resolve chain. Then the log message is added.