0

So, if you can determine when an image has finished loading with jQuery, is it exactly the same with multiple images?

Community
  • 1
  • 1
Lucas
  • 16,930
  • 31
  • 110
  • 182
  • if you use $('img').load(/*FN*/) in this case you /*FN*/ will be executed for each img, not once. Could specify in more detila what do you need? – Anton Baksheiev Sep 25 '12 at 09:45

2 Answers2

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();
}

demo

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