재귀 함수 호출로 $.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();
});
}
}
는 스크립트가 동시에 요구되고 있다는 점이다 그들이 비동기 적으로로드하기 때문에, 그들은 돌아가 임의의 순서로 실행합니다.
업데이트
나는이 테스트를하지 않은,하지만 스크립트가 로컬 호스트하는 경우, 당신은 다음, 일반 텍스트를 검색하는 사람들이 모두로드 될 때까지 변수에 모든 코드를 저장하기 위해 시도 할 수 당신의 각 기능에 분류 사용해서
var sorted = scripts.sort();
및 -) (
이
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*/ }
});
});
아, 닌자. 그래도 좋은 일. –
이것이 작동하는 것 같습니다!, 감사합니다. 아주 좋은 설명입니다! – greenbandit