gpt4 book ai didi

jQuery:按顺序加载脚本

转载 作者:行者123 更新时间:2023-12-03 22:19:25 25 4
gpt4 key购买 nike

我正在尝试使用 jQuery 动态加载一些脚本:

var scripts = ['script1.js','script2.js','script3.js'];

$.each(scripts , function(i, val) {
$.getScript(val, function() {
console.log('loaded '+ val);
});

但有时加载脚本的顺序会发生变化。在成功加载前一个脚本后,如何加载每个脚本?

最佳答案

您可以在前一个加载完成后通过使用 $.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 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:按顺序加载脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9711160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com