3 回答
TA貢獻1818條經驗 獲得超8個贊
答案是
您可以使用promises getScript()并等待所有腳本都加載,例如:
$.when(
$.getScript( "/mypath/myscript1.js" ),
$.getScript( "/mypath/myscript2.js" ),
$.getScript( "/mypath/myscript3.js" ),
$.Deferred(function( deferred ){
$( deferred.resolve );
})).done(function(){
//place your code here, the scripts are all loaded});在上面的代碼中,添加一個Deferred并將其解析為內部$()就像在jQuery調用中放置任何其他函數一樣$(func),就像它一樣
$(function() { func(); });即它等待DOM準備就緒,因此在上面的例子中$.when等待加載所有腳本并且由于$.Deferred在DOM就緒回調中解析的調用而使DOM準備就緒。
對于更通用的用途,一個方便的功能
可以像這樣創建一個接受任何腳本數組的實用程序函數:
$.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);}可以像這樣使用
var script_arr = [
'myscript1.js',
'myscript2.js',
'myscript3.js'];$.getMultiScripts(script_arr, '/mypath/').done(function() {
// all scripts loaded});路徑將被添加到所有腳本的位置,并且也是可選的,這意味著如果數組包含完整的URL,那么也可以執行此操作,并將所有路徑全部放在一起
$.getMultiScripts(script_arr).done(function() { ...爭論,錯誤等
另外,請注意done回調將包含許多與傳入腳本匹配的參數,每個參數表示包含響應的數組
$.getMultiScripts(script_arr).done(function(response1, response2, response3) { ...每個數組都包含類似的內容[content_of_file_loaded, status, xhr_object]。我們通常不需要訪問這些參數,因為無論如何都會自動加載腳本,并且大部分時間done回調都是我們真正知道所有腳本都已加載的,我只是為了完整而添加它,以及在需要訪問加載文件的實際文本或需要訪問每個XHR對象或類似內容的極少數情況下。
此外,如果任何腳本無法加載,將調用失敗處理程序,并且不會加載后續腳本
$.getMultiScripts(script_arr).done(function() {
// all done
}).fail(function(error) {
// one or more scripts failed to load
}).always(function() {
// always called, both on success and error
});
TA貢獻1783條經驗 獲得超5個贊
您可以嘗試使用遞歸。這將一個接一個地同步下載它們,直到它完成下載整個列表。
var queue = ['url/links/go/here'];ProcessScripts(function() { // All done do what ever you want}, 0);function ProcessScripts(cb, index) {
getScript(queue[index], function() {
index++;
if (index === queue.length) { // Reached the end
cb();
} else {
return ProcessScripts(cb, index);
}
});}function getScript(script, callback) {
$.getScript(script, function() {
callback();
});}TA貢獻1796條經驗 獲得超4個贊
以下是使用Maciej Sawicki的答案并實現Promise回調:
function loadScripts(urls, path) {
return new Promise(function(resolve) {
urls.forEach(function(src, i) {
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = (path || "") + src;
script.async = false;
// If last script, bind the callback event to resolve
if(i == urls.length-1) {
// Multiple binding for browser compatibility
script.onreadystatechange = resolve;
script.onload = resolve;
}
// Fire the loading
document.body.appendChild(script);
});
});}使用:
let JSDependencies = ["jquery.js", "LibraryNeedingJquery.js", "ParametersNeedingLibrary.js"];loadScripts(JSDependencies,'JavaScript/').then(taskNeedingParameters);
所有Javascript文件都會盡快下載并按給定順序執行。然后taskNeedingParameters被叫。
添加回答
舉報
