Question

Hopefully someone can help me out here.

In my application I am making some quite large AJAX calls, getting HTML to drop into my page. This HTML could contain up to 7 or 8 images.

I am currently using AJAX like this:

$.ajax({
    type: 'GET',
    url: 'ajax-content/page.html'
}).done(function(data) {

    $('#case_study').html('<div class="loading"></div>');

    $('#case_study').append(data);

    // EVERYTHING AFTER THIS POINT SHOULD ONLY RUN ONCE ALL CONTENT IS
    // SUCCESSFULLY LOADED ON THE PAGE

    $('#case_study').css("max-height", "3000px");

    $('.loading').remove();

}).fail(function(data) {

    console.log("FAIL");
    console.log(data);

});

Now this all works fine, but, the code in .done runs as soon as the server has responded with my HTML, this is great, but not exactly what I am looking for.

What I need to know is, after I have run $('#case_study').append(data) when is all of the content actually visible to the user, when have all the images finished loading etc.

If anyone can help me work out how to do this that would be fantastic.

Cheers.

Was it helpful?

Solution

If you are only waiting for the images you could add an eventListener to the images and wait for them all the finished loading:

var index = 0;
$('img').on('load', function() {
    index++;
    if (index == $('img').length - 1) {
        // show your content
    }
});

OTHER TIPS

Did you try the load function of jQuery?

$.ajax({
    type: 'GET',
    url: 'ajax-content/page.html'
}).done(function(data) {

    $('#case_study').html('<div class="loading"></div>');

    $('#case_study').append(data).load(function() {
      $('#case_study').css("max-height", "3000px");

      $('.loading').remove();
    });

}).fail(function(data) {

    console.log("FAIL");
    console.log(data);

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top