2016-07-03 36 views
3

我正在使用jQuery getScript将X数量的js文件加载到我的页面中。每个JS页面都有一个AJAX调用,用于从数据库中提取数据。如何知道何时使用getScript完成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); 
} 
+0

让所有的程序写的完成状态的地方。然后,您需要查询“某处”(服务器,localStorage或其他)以检查所有过程是否已完成。 – pah

+0

@threadp我该如何去等待或检查类似的东西的状态? – SBB

+0

安装一个'setTimeout'处理程序,它检查是否完成,如果一切都完成(加载),则执行进一步的代码。 – pah

回答

5

您可以使用.ajaxStop()

每当一个Ajax请求完成后,jQuery的检查是否有 任何其他优秀的Ajax请求。如果不存在,jQuery将触发 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调用到第二阵列

"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

+0

好吧,这真是太酷了 - 我认为这将解决我的需求。 – SBB

+0

@SBB查看更新后的帖子 – guest271314

相关问题