Eleeist
Eleeist

Reputation: 7041

jQuery wait till AJAX page is fully loaded

I use AJAX to display content of page B on page A.

How can I make jQuery wait for everything to load (text, images etc.) before the content is displayed?

$.ajax({
    url:"pageB.html",
    beforeSend: function() {
        //show loading animation here
    }
    success: function(data) {
        //hide loading animation here
        $("body").append(data);
    }
});

I use beforeSend to show a loading animation to the user when the AJAX request is being processed. Now I want to "extend" the waiting time so that the loading animation does not disappear until all images are loaded.

I tried to initially hide appended data, wait for all images to load and then show content - $("body").on("load", "images class here", function() {//show content}) inside success but the event does not appear to fire.

Any ideas?

UPDATE:

Updated code:

$.ajax({
    url:"pageB.html",
    beforeSend: function() {
        //show loading animation here
    }
    success: function(data) {
        //hide loading animation here
        $("body").append(data);
        $("body").on("onload", "img", function() {//display content});
    }
});

Upvotes: 1

Views: 13921

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

You'll have to use direct event binding:

$("body img").on("load", function () { });
$("body .image-class").on("load", function () { });

Rather than delegated binding:

$("body").on("load", "img", function() { });
$("body").on("load", ".image-class", function () { });

Delegated bindings depend on the event bubbling, which not every event does. And it seems the "load" event -- at least, from an <img> -- is one that doesn't.

Example: http://jsfiddle.net/DLy6j/

Upvotes: 4

lukas.pukenis
lukas.pukenis

Reputation: 13587

In case of images you need to catch onload event for all the images. So once you get success callback, find all the images, add "onload" event, and calculate once all the images have been loaded.

Upvotes: 0

Related Questions