Using $.Deferred to Group AJAX Requests

I am working on a project that contains a lot of charts. Since the data driving the charts could take some time to load I am making each chart load asynchronously using jQuery's ajax functions.

This has worked great, but I noticed that some of the charts are using the same dataset, just charted differently causing the same data to be requested multiple times from the server. One way to handle the duplicate requests is to use the jQuery Deferred Object when making requests.

In order to group the requests together I needed a way to determine if I already have one just like the request going through. To make this simple I used a MD5 library and JSON.stringify() to create a hash of the data that I am sending to the server.

If the hash is unique then I add a deferred object and make the ajax call. Otherwise, I bind to the previous deferred object and wait for the request to finish. Since we are using the jQuery Deferred object the callback will still have the data even if there is a gap between the original ajax request.

Here is a simplified example:

Posted on 14 Feb 2012

comments powered by Disqus