6

I have a callback function that I'd like to execute after 2 separate $.getScript calls have successfully loaded.

I'm using the below design, but it feels messy, and the use of a named function feels very un-jQuery

var foo_ready = false;
var bar_ready = false;
var dual_callback = function(){
    if(foo_ready && bar_ready)
    {
        //do things
    }
};

 jQuery.getScript('/foo.js', function(){
        foo_ready = true;
        dual_callback();
    });
 jQuery.getScript('/bar.js', function(){
        bar_ready = true;
        dual_callback();
    });

Is there a better or more elegant way to do execute a single callback after multiple asynchronous calls have completed?

0

1 Answer 1

12

If you have jQuery 1.5.1 you can do this:

$.when( $.getScript('/foo.js'), $.getScript('/bar.js') ).done(function(){ 
     // this is called when both are done.
});

Check out the Deferred Object and $.when()

Sign up to request clarification or add additional context in comments.

1 Comment

Very cool. +1. I hadn't read about $.when() yet; for my particular purposes, I don't have access to 1.5.1; I'm stuck in the doldrums of 1.4.2, for now ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.