Let’s say I have a situation like so:
$(window).load(function() {
$("body").append("<div id='container'></div>");
var i=1;
for ( i=1; i<=10; i++ ) {
$("#container").append("<img src='img"+i+".jpg'></img>");
}
});
Which will load 10 random images which can be different sizes (img1.jpg…jp10.jpg). Now let’s say I need some property from these images. For example, the total height combined of the 10 loaded images. This requires all the images to be loaded before we can use .height().
Now the question:
How can I wait until all images are loaded before I start the calculation? Or even more general, how can I wait until all images in some given container are loaded before I execute a function?
With 1 image, I can use .load() and have a callback function. But with multiple images, does not seem very easy. One solution would be to add a .load() to every image that adds to a counter, and once that counter reaches a certain value, then execute the function. Seems a tiny bit hacky (but not TOO hacky). Just wanted to get some opinions on this matter.
You could create those images with jQuery aswell and attach an
onload-eventhandler for those either. Also you could combine that with jQuery’s Deferred objects to link things together. That might look like:In that constelation, the
donehandler will only fire if all images could get loaded successfully. If you want to know if at least one image failed loading, you could also bind anerrorevent handler andreject()a promise. Finally use.then( success, failure )instead of.done().By the way, I guess it makes more sense to put that code into the
DOMContentLoaded(jQuery’s.ready()).