I want to execute some code only when all images in a jQuery object have loaded. I can do this as follows:
var img1Load = $.Deferred();
$('#img1').load(img1Load.resolve);
var img2Load = $.Deferred();
$('#img2').load(img2Load.resolve);
$.when(img1Load, img2Load).done(function(){
console.log('both imgs loaded');
});
This is OK, but I would like to not have to define a separate deferred object for every image. What if there are hundreds of them or if they may or may not be present on a given page? I would like to do it all at once, with something like:
$.when(allImagesHaveLoaded).done(function(){
console.log('all imgs loaded');
});
I have tried creating an allImagesHaveLoaded function which iterates over the images, creating a new deferred object for each. The trouble is, if I return an array of these to be used as the parameter for a when, it doesn’t work (because it’s not a deferred object, it’s an array of deferred object).
I fiddled around with $.Deferred.pipe a bit as well (to try to create a chained deferred object to pass to when), but that didn’t appear to help.
Is there a sensible way of doing this?
There is a way to pass an array of deferred objects to
$.when: