我正在使用jQuery getScript将X数量的js文件加载到我的页面中。每个JS页面中都有一个AJAX调用,该调用从数据库中获取数据。
getScript
我正在使用该.done方法getScript查看何时已加载所有文件,但我需要等待所有AJAX调用也已完成。
.done
我该如何做才能等待AJAX调用在包含的文件中完成getScript?
$.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()
.ajaxStop()
每当Ajax请求完成时,jQuery都会检查是否还有其他未完成的Ajax请求。如果不存在,jQuery将触发该ajaxStop事件。
ajaxStop
$(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调用推入第二个数组
$.when.apply()
"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