Tom Auger
Tom Auger

Reputation: 20101

jQuery.ajax() page load doesn't complete until all XHRs finish loading?

I'm pretty new to Ajax, but I thought the point of using it was the 'Asynchronous' part. Unfortunately, I seem to be stuck in synchronous hell.

Early in my page, a number of elements are created, each with a unique ID.

At the very end of my page, using jQuery I iterate over each element and issue an ajax() call (where I explicitly set 'async' to true!). Currently on complete, each Ajax call just populates the corresponding element with some text output. Eventually it will be an IMG.

What occurs is that I get the "busy" mouse cursor on the page and certain elements do not populate until all (17) XHR requests come back.

Here's my jQuery call:

jQuery('.ajax-item').each(function(index){
    $item = jQuery(this);
    ID = $item.attr('id');

    //$item.load(WPGlobals.ajaxurl, { 'action' : 'my-action', 'ID' : ID });
    jQuery.ajax({
        url : WPGlobals.ajaxurl,
        type : 'POST',
        async : true,
        data : { 'action' : 'my-action', 'ID' : ID },
        success : function(response){ $item.html(response) }
    });
});

Looking at this code (above) you will note that this is a WordPress site (though I don't know what that would have to do with anything), and that I also tried the simpler load() method, and switched to ajax() so I could force async : true in case there was any funny messing around with the Globals as a result of some WP weirdness.

Am I going about this the right way? Shouldn't my page load regardless of the AJAX and then those items will just lazily populate when the XHRs come in?

EDIT - I just noticed that my logic is messed in the static call; I probably need a closure in order to get $item to scope properly, but that's neither here nor there as far as the async issue - it still fires off 17 XHRs and waits for them all to come home before the page load is complete.

Upvotes: 0

Views: 897

Answers (1)

Jake Feasel
Jake Feasel

Reputation: 16955

I believe you are hitting a maximum number of requests limit, and so your browser is waiting until more threads become available. Check out this thread: How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

Upvotes: 4

Related Questions