Example sharing using when in jQuery to implement multiple AJAX requests corresponding to a single callback

  • 2020-03-30 02:43:17
  • OfStack

  I knew that these functions were asynchronously executed and returned with a delay, so I wondered if there was a way I could use a single callback to load them in parallel, as the JS loader curljs did. Very lucky! With jQuery. When, I can load two requests concurrently and execute only one callback!

The jQuery script
As I mentioned, here is the use case for the load script and a JSON resource:


$.when(
 $.getScript('/media/js/wiki-min.js?build=21eb633'), 
 $.getJSON('https://developer.mozilla.org/en-US/demos/feeds/json/featured/')
).then(function(a, b) {  //Or you can use ".done"
 //Yay, load done, here we can do some dependency operations...
});

When the resource is loaded, the specified done or then callback fires, so you know the request has completed. Each request returns a different type of callback parameter object, so the above request may return the following information:


//Format: [response, state, JQXHR], [response, state, JQXHR]
["(function(c){var e=c(".from-search-navigate");if(e ... ;if(j){g.apply(m,l)}}}})(window,document,jQuery);", "success", Object]
[Array[15], "success", Object]

If we also need to add a traditional AJAX XHR request, such as a widget template, we can do this:


$.when(
 $.getScript('/media/js/wiki-min.js?build=21eb633'), 
 $.getJSON('https://developer.mozilla.org/en-US/demos/feeds/json/featured/'), 
 $.get('/')
).then(function(a, b, c) { 
 console.log(a, b, c); 
});

The Dojo Toolkit has been around for a long time, but I'm excited that jQuery can do the same. With today's development, it's a natural requirement to share the same callback with multiple requests that are out of sync and return in uncertain order, so jQuery is definitely moving with The Times!


Related articles: