一尘不染

jQuery:按顺序加载脚本

ajax

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

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

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

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


阅读 352

收藏
2020-07-26

共1个答案

一尘不染

您可以通过使用回调函数$.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*/ }
    });
});
2020-07-26