我使用jQuery getScript将X量的js文件加载到我的页面中.每个JS页面都有一个AJAX调用,用于从数据库中获取数据.
我在getScript上使用.done方法来查看所有文件的加载时间,但我需要等到所有的AJAX调用都完成.
在做某事之前,我怎样才能通过getScript等待AJAX调用完成包含的文件?
$.getMultiScripts(moduleIncludes, 'includes/js/modules/').done(function() {
// All of the JS files have been included but we need to wait until those files have finished their AJAX call.
});
// Get array of JS scripts to load
$.getMultiScripts = function(arr, path) {
var _arr = $.map(arr, function(scr) {
return $.getScript((path || "") + scr);
});
_arr.push($.Deferred(function(deferred) {
$(deferred.resolve);
}));
return $.when.apply($, _arr);
}
解决方法:
你可以使用.ajaxStop()
Whenever an Ajax request completes, jQuery checks whether there are
any other outstanding Ajax requests. If none remain, jQuery triggers
theajaxStop
event.
$(document).on("ajaxStop", function() {
// do stuff when all `$.ajax()` call have complete
$(document).off("ajaxStop")
});
$.getMultiScripts(moduleIncludes, 'includes/js/modules/').done(function() {
// All of the JS files have been included but we need to wait until those files have finished their AJAX call.
});
另一种方法是使用$.when.apply()两次.也就是说,将ajax调用推入第二个数组
“module1.js”
data.push($.get("/path/to/module1-resource"))
var modules = ["module1.js", "module2.js", "module3.js"];
// declare global `data` array
data = [];
$.getMultiScripts = function(arr, path) {
var _arr = $.map(arr, function(scr) {
return $.getScript(scr)
});
return $.when.apply($, _arr.concat($.when()))
}
$.getMultiScripts(arr)
.then(function() {
console.log("getScript calls", arguments)
$.when.apply($, data).then(function() {
console.log("ajax calls", arguments)
})
});
plnkr http://plnkr.co/edit/si2EsUZOciOwU4nAPlS9?p=preview
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。