I've been working on a new feature for the Mozilla Developer Network which requires loading of a basic script file as well as a JSON stream. Since we use jQuery, that means a jQuery.getScript
and a jQuery.getJSON
. I know those both work asynchronously and return a Deferred, so I wondered if there was a way that I could load them in parallel with one callback, much the way JavaScript loaders like curljs do. I was in luck! Using jQuery.when
, I can load both requests concurrently with one callback!
我一直在为Mozilla开发人员网络开发一项新功能,该功能需要加载基本脚本文件以及JSON流。 由于我们使用jQuery,因此意味着jQuery.getScript
和jQuery.getJSON
。 我知道它们都异步工作并返回Deferred,所以我想知道是否有一种方法可以与一个回调并行地加载它们,就像curl加载器一样。 我很幸运! 使用jQuery.when
,我可以通过一个回调同时加载两个请求!
jQuery JavaScript (The jQuery JavaScript)
As I mentioned, my use case was loading a script and a JSON resource, so how it works is:
正如我提到的,我的用例是加载脚本和JSON资源,因此其工作方式是:
$.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 ".done"
// Yay, stuff loaded and now we can do something!
});
When the resources are done loading, the done
or then
callback fires and I know the requests are complete. Each request type provides a different callback argument object, so the above would provide:
当资源加载完成,在done
或then
回调火灾,我知道的要求是完整的。 每种请求类型都提供一个不同的回调参数对象,因此上述内容将提供:
// [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 wanted to add a traditional AJAX XHR request to the mix, say a widget template, we could do that too:
如果我们想向混合中添加传统的AJAX XHR请求,例如一个小部件模板,我们也可以这样做:
$.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 had this type of functionality for a long time but I'm stoked that modern jQuery allows for the same. Making multiple requests with one callback seems as relevant as any other task these days, so jQuery's definitely moving with the times!
Dojo Toolkit拥有这种功能已经很长时间了,但是我很高兴现代jQuery允许相同的功能。 如今,使用一个回调发出多个请求似乎与其他任何任务都相关,因此jQuery肯定与时俱进!