Вы можете загрузить каждый после того, как предыдущая завершила загрузку, используя функцию обратного вызова $.getScript()
в качестве рекурсивного вызова функции.
//setup array of scripts and an index to keep track of where we are in the process
var scripts = ['script1.js','script2.js','script3.js'],
index = 0;
//setup a function that loads a single script
function load_script() {
//make sure the current index is still a part of the array
if (index < scripts.length) {
//get the script at the current index
$.getScript(scripts[index], function() {
//once the script is loaded, increase the index and attempt to load the next script
console.log('Loaded: ' + scripts[index]);
index++;
load_script();
});
}
}
Что происходит в вашем коде является то, что скрипты испрашивается в то же время и с тех пор они загружаются асинхронно, они возвращаются и выполняются в случайном порядке.
Update
Я не проверял, но если скрипты размещаются локально, то вы могли бы попытаться получить их в виде обычного текста, а затем хранить весь код в переменных, пока все они не будут загружены, на которых время вы могли бы оценить сценарии в следующем порядке:
var scripts = ['script1.js','script2.js','script3.js'],
//setup object to store results of AJAX requests
responses = {};
//create function that evaluates each response in order
function eval_scripts() {
for (var i = 0, len = scripts.length; i < len; i++) {
eval(responses[scripts[i]]);
}
}
$.each(scripts, function (index, value) {
$.ajax({
url : scripts[index],
//force the dataType to be `text` rather than `script`
dataType : 'text',
success : function (textScript) {
//add the response to the `responses` object
responses[value] = textScript;
//check if the `responses` object has the same length as the `scripts` array,
//if so then evaluate the scripts
if (responses.length === scripts.length) { eval_scripts(); }
},
error : function (jqXHR, textStatus, errorThrown) { /*don't forget to handle errors*/ }
});
});
Ahh, ninja'd. Хорошая работа. –
это, кажется, работает !, спасибо и очень приятное объяснение! – greenbandit