Running jQuery code after page finishes loading AJAX content
Question
I have a page that loads content through AJAX. Among this content are some images. I need to do some formatting to the page layout depending on the images sizes (which vary) but in order to get the sizes, I need the images to finish loading first before running the code. If it was in an ordinary page (content loading normally WITHOUT AJAX), all I have to do is use the $(window).load()
function but with AJAX it doesn't trigger for some reasons. I need a workaround to this : a way to execute some code after the images loaded through AJAX finish loading.
Basically, this is what I'm trying to do
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("results").innerHTML=ajaxRequest.responseText;
//the responseText includes images among other information to be loaded
$(window).load(function() {
...some code
});}}
but the $(window).load()
never fires and I need to run the code once ALL images have finished loading so binding a load event to every image isn't really an option.
I have another question that is related and similar to the first one : the jQuery $(document).ready
doesn't seem to fire either after content is loaded through AJAX. I don't need it right now but I will certainly do in the future, so any workarounds for this too ?
I would really appreciate your help and thanks a lot.
Solution
$(window).load works only for the page initial loading.
The only clean solution I see is counting the images (hoping they're the only problem) and waiting for them to load :
$('#results').load('youurl', function() {
var $images = $('#contenu img');
var count = $images.length;
console.log('initial images count : ', count);
var decrement = function() {
if (--count==0) {
console.log('All images loaded');
// do something
}
};
$images.each(function(){
if (this.complete) {
decrement();
} else {
this.onload = function(){
decrement();
};
}
});
});
This is now testable on this site : click a link for a recipe and look at the console.
OTHER TIPS
I believe what you want is the imagesLoaded plugin. After loading the markup via AJAX, select the images inside this div and call .imagesLoaded()
on them:
$('.article img').imagesLoaded( myCallbackFunction );
Besides, you use the XMLHttpRequest... it's much easier with JQuery. You can get rid of all the code you posted and simply do:
$("#results").load("ajaxpage.php", function() { ... some code... });
Is all that you need. If you need to fire some code when the window is loaded, use your $(window).load(). If you need to fire the code after the ajax request, just put it in the callback function() above