3

Possible Duplicate:
Multiple ajax calls inside a each() function.. then do something once ALL of them are finished?

Basically, I want to run a function after an each() loop containing load() for each loop completely finishes. It takes some time to load each link and is waiting for the browser to catch up but the script has already moved on to the next step. Any ideas?

jQuery('#theId a').each(function() { // contains many links
    toLoad = jQuery(this).attr('href');
    jQuery('#containment').load(toLoad, function(response) {
       //do stuff
    });
 });

//... Do stuff after the above is really complete.
Community
  • 1
  • 1
  • use the index parameter of each() to count down the objects and use the callback of the load for a condition – ggzone Feb 10 '12 at 17:24
  • 1
    The best way to do this is using deferred objects. I was about to post an example but saw the link above. Use the top answer from that question. – James Allardice Feb 10 '12 at 17:29
  • Couldn't you first add a class to the last element (`$('a:last').addClass('lastlink');`) and then when you're iterating through all the links and running load(), just call a function containing all the stuff you want to execute from the load() callback if the element you're on has the class you assigned earlier ('lastlink')? – j08691 Feb 10 '12 at 17:32
  • @j08691 - What if one of the earlier asynchronous requests hadn't returned yet? – James Allardice Feb 10 '12 at 17:35

1 Answers1

5

Try something like this:

var e = jQuery("#theId a"), l = e.length;
e.each(function() {
    toLoad = this.attr("href"); // I'm fairly sure "this" is already a jQuery object
    jQuery("#containment").load(toLoad, function(response) {
        // do stuff
        l--;
        if( l == 0) {
            // this is the last one - do ending stuff here.
        }
    });
});

If "this" isn't already a jQuery object, just revert that line to what you have.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592