SverkerSbrg
SverkerSbrg

Reputation: 503

jQuery .lastLoad of several events

I'm loading remote content into several divs and want to measure them and compare the results when all have loaded. What is the best way to get this event?

pseudo code:

$("#div1").load("www.foo.com/1");
$("#div2").load("www.foo.com/2");
$("#div3").load("www.foo.com/3");

function div1_and_div2_loaded(){
    alert("Success!");
}

Upvotes: 1

Views: 22

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337656

You can use $.when() to execute code when a set of AJAX requests have completed. You will need to amend your code to use $.ajax though, as load does not return a deferred object. Try this:

var request1 = $.ajax({
    url: 'http://www.foo.com/1',
    success: function(response) {
        $('#div1').html(response);
    }
})

var request2 = $.ajax({
    url: 'http://www.foo.com/2',
    success: function(response) {
        $('#div2').html(response);
    }
})

$.when(request1, request2).done(function() {
    alert('success!');
});

The advantage of this pattern is that all* the requests will execute simultaneously, leading to a faster overall loading time.

*The browser may queue requests if you are making a lot of them.

Obviously you need to DRY up the creation of the requests, this is just a quick and dirty example.

Upvotes: 1

Related Questions