Daniel Hoelbling-Inzko talks about programming

Execute callback once multiple ajax requests finish with jQuery

Posted by Daniel Hölbling on September 26, 2011

I just stumbled upon the problem of having to load multiple resources during page initialization. During the initial load I wanted a way to prevent any animations and other fancy stuff from happening but rather only create the page as soon as possible.

Since I couldn't find any way in jQuery (there are no combined callbacks) I decided to implement this using the deferred promise concept jQuery 1.5 introduced.

Deferred basically means "I represent a ajax call that has happened or is happening - ask me about it and I'll tell you when it's done or was done already". So implementing my little wait functions was rather trivial:

I used CoffeeScript for this, but the resulting JavaScript is also quite readable and you can use that too.

What this does is provide you with the awkwardly named function waitForAjaxRequestsToComplete that takes one callback parameter and an array of jQuery promises. Once all promises succeed or fail the callback will be called and the first parameter will contain information about failures.

Sample usage:

waitForAjaxRequestsToComplete(function (info) {
  console.log("requests failed " + info.failures)
  console.log("requests succeeded " + info.successes)
  console.log(info.failed) //contains all failed promises
}, [ $.ajax(...), $.ajax(...), $.ajax(...) ]);

comments powered by Disqus

My Photography business


dynamic css for .NET