If you have just inserted a bunch of HTML into your document (containing some <img>
tags) and you want to know when all those new images are loaded, you can do it like this. Let's suppose that the dynamic content was all inserted into the #root
object. Right after you've inserted the dynamic contend, you can run this code:
function notifyWhenImagesLoaded(rootSelector, callback) {
var imageList = $(rootSelector + " img");
var imagesRemaining = imageList.length;
function checkDone() {
if (imagesRemaining === 0) {
callback()
}
}
imageList.each(function() {
// if the image is already loaded, just count it
if (this.complete) {
--imagesRemaining;
} else {
// not loaded yet, add an event handler so we get notified
// when it finishes loading
$(this).load(function() {
--imagesRemaining;
checkDone();
});
}
});
checkDone();
}
notifyWhenImagesLoaded("#root", function() {
// put your code here to run when all the images are loaded
});
You call this function after you've inserted the dynamic content. It finds all images tags in the dynamic content and checks if any have already loaded. If they have, it counts them. If they haven't, then it installs a load event handler so it will get notified when the image loads. When the last image finishes loading, it calls the callback.