So, if you can determine when an image has finished loading with jQuery, is it exactly the same with multiple images?
Asked
Active
Viewed 62 times
2 Answers
1
Created a Deferred
object for each image that is being loaded, and store them in an array.
As each image's .load()
callback is called, resolve
the associated deferred object and then use $.when()
to call a final callback only when all of the promises have been resolved:
function onAllLoaded(imgs, callback) {
var i, n, a = [];
for (i = 0, n = imgs.length; i < n; ++i) {
a[i] = $.Deferred();
$(imgs[i]).on('load', a[i].resolve); // not using .onload to avoid clashes
}
$.when($, a).done(callback);
}
Be aware that on some browsers (early IE?) you need to take special measures to ensure that the .load
callback actually happens. That's out of scope of this answer.

Alnitak
- 334,560
- 70
- 407
- 495
1
You can do it easily :
function onloadall(images, callback) {
var n = 0;
for (var i=0; i<images.length; i++) {
if (!images[i].width) {
n++;
images[i].onload = function(){
if (--n==0) callback();
}
}
}
if (n==0) callback();
}

Denys Séguret
- 372,613
- 87
- 782
- 758