Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
-6
rated 0 times [  0] [ 6]  / answers: 1 / hits: 15489  / 13 Years ago, mon, april 11, 2011, 12:00:00

This is the code I use to preload images, I'm not sure if it's the best one.
My question is, how can I fire and event, for an example alert(); dialog after is has finished loading all the images?



var preload = [a.gif, b.gif, c.gif];
var images = [];
for (i = 0; i < preload.length; i++) {
images[i] = new Image();
images[i].src = preload[i];
}

More From » jquery

 Answers
20

You can use the new $.Deferred if you like:



var preload = [a.gif, b.gif, c.gif];
var promises = [];
for (var i = 0; i < preload.length; i++) {
(function(url, promise) {
var img = new Image();
img.onload = function() {
promise.resolve();
};
img.src = url;
})(preload[i], promises[i] = $.Deferred());
}
$.when.apply($, promises).done(function() {
alert(All images ready sir!);
});


Might be a little risky to leave the Image objects floating around, but if so that could be fixed easily by shifting the closure. edit in fact I'll change it myself because it's bugging me :-)


[#92808] Saturday, April 9, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristineterrak

Total Points: 74
Total Questions: 109
Total Answers: 115

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;