jQuery的:为了加载脚本 [英] jQuery: load scripts in order
问题描述
我试图动态加载一些脚本使用jQuery:
I'm trying load some scripts dynamically with jQuery:
var scripts = ['script1.js','script2.js','script3.js'];
$.each(scripts , function(i, val) {
$.getScript(val, function() {
console.log('loaded '+ val);
});
但有时加载脚本变化的顺序。在previous一个人成功加载后,我怎么能装载每个脚本?
But sometimes the order of loaded scripts changes. How can I load each script after the previous one has successfully loaded?
推荐答案
您可以以后previous装载每个已使用 $的回调函数加载完毕。getScript加入脚本()
作为一个递归函数调用。
You can load each after the previous has finished loading by using the callback function of $.getScript()
as a recursive function call.
//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();
});
}
}
什么是您的code发生的是,脚本被请求的同时,并因为异步加载,他们返回并以随机顺序执行。
What's occurring in your code is that the scripts are being requested at the same time and since they load asynchronously, they return and execute in random order.
我没有测试过这一点,但如果脚本本地托管的,那么你可以尝试检索它们在纯文本,然后将其存储在变量中的所有code,直到全部加载它们,此时你可以为了评估该脚本:
I haven't tested this, but if the scripts are hosted locally, then you could try to retrieve them in plain text, then store all of the code in variables until they are all loaded at which time you could evaluate the scripts in order:
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*/ }
});
});
这篇关于jQuery的:为了加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!