Sajjan Sarkar Sajjan Sarkar - 1 year ago 61
Javascript Question

Image Preloader Callback firing before all images have loaded


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

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() {
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!");

return $defer;

var images = ['', '', '', '', ''];

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


Console Output:

enter image description here


Answer Source

Swap these two lines

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

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