I am dynamically loading content in a page using jQuery Ajax. The content contains images, so I need to know at what point all the images will be loaded, something like DOM Ready.
Initially content will be hidden. After the images were loaded successfully I display the div containing them. Is there a method to detect when the loaded content with Ajax is ready to display? Ajax success
function is called when the text response is returned from server but I need to execute a function when is all loaded and images are loaded as well.
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.