简体   繁体   English

在运行javascript代码之前,如何使用jQuery.getScript()加载可变数量的脚本?

[英]How do I load a variable number of scripts with jQuery.getScript() before running javascript code?

I need to load a variable number of javascript source files before running javascript code that depends on them. 我需要在运行依赖于它们的javascript代码之前加载可变数量的javascript源文件。 Sometimes 1 script needs to be loaded, other times 2. The getScript() method allows one script to be loaded - how could I use it to load x number of scripts before running its inner code? 有时需要加载1个脚本,有时需要加载2. getScript()方法允许加载一个脚本 - 如何在运行内部代码之前使用它来加载x个脚本?

$.getScript("test.js", function(){
    // code to run after script is loaded
});

What I need: 我需要的:

$.getScript(new Array("1.js","2.js"), function(){
    // code to run after all scripts are loaded
});

Thanks 谢谢

If you are using jquery 1.5 you can use the new deferred syntax. 如果您使用的是jquery 1.5,则可以使用新的延迟语法。

$.when(
    $.getScript("1.js"), 
    $.getScript("2.js"), 
    $.getScript("3.js")
).then(function(){
    alert("all loaded");
});

Just pass in the scripts you wish to load. 只需传入您要加载的脚本即可。

I suggest you look into LABjs 我建议你研究一下LABjs

That is exactly what its purpose is. 这正是它的目的。

I've use RequireJS quite extensively and it's very good. 我非常广泛地使用RequireJS ,它非常好。 However, this might work for you: 但是,这可能对您有用:

$.getScript("1.js", function(){
    $.getScript("2.js", function () {
        // code to run after all scripts are loaded
    });
});

That's a pretty nasty and little block of code there, IMO, but if it is actually only two scripts like that, it's probably worth it. 这是一个非常讨厌和很少的代码块,IMO,但如果它实际上只有两个这样的脚本,它可能是值得的。 The logic of the above could also be extracted to a generic function, but once you go too far down that path, it's probably smarter to use RequireJS, or LABjs as JAAulde suggested. 上面的逻辑也可以被提取到一个通用函数,但是一旦你走得太远,使用RequireJS或者像JAAulde建议的LABjs可能更聪明。

One way is to list all your scripts in an array, track how many scripts have loaded vs. the amount you want to load. 一种方法是列出阵列中的所有脚本,跟踪已加载的脚本数量与要加载的数量。 Something like this: 像这样的东西:

var toLoad = ["1.js", "2.js", "3.js"], loaded = 0;

var onLoaded = function() {
    loaded++;
    if (loaded == toLoad.length) {
        console.log('All scripts loaded!');
    } else {
        console.log('Not all scripts are loaded, waiting...');
    }
}

for (var i = 0, len = toLoad.length; i < len; i++) {
    $.getScript(toLoad[i], onLoaded);
}    

Loading multiple scripts by $.getScript() one after the other and do stuff after all the scripts are loaded 一个接一个地加载$ .getScript()加载多个脚本,并在加载所有脚本后执行操作

Working Fiddle . 工作小提琴 Check the Console window for the output 检查控制台窗口以获取输出

We can create a function to which we pass array of js file paths, this function will do a $.getScript() for the first js file and on success method it will call the same function by passing the second js file index, and this on success will call the same function by passing 3rd file index and so on until it loads the last file. 我们可以创建一个传递js文件路径数组的函数,这个函数将为第一个js文件执行$.getScript() ,在成功方法上,它将通过传递第二个js文件索引来调用相同的函数,这个成功将通过传递第三个文件索引来调用相同的函数,依此类推,直到它加载最后一个文件。 So its basically a recursion function which will give a callback when all the files in the array has been loaded.The end code would be as simple as 所以它基本上是一个递归函数,当数组中的所有文件都被加载时会给出回调。结束代码就像一样简单

LoadAllScripts("yourArray",function(){
  alert("all scripts loaded!!");
 });

So the complete code would go like this. 所以完整的代码就是这样的。

 var LoadAllScripts = function (scriptArray, callback) {   
   SyncLoadScript({ scriptArray: scriptArray, index: 0}, function () {
        callback();
    });
};

And SyncLoadScript ( core of the logic ) looks like 而SyncLoadScript( core of the logic )看起来像

 var SyncLoadScript = function (scriptConfig, callback) {
    var $this = this;
    var script = scriptConfig.scriptArray[scriptConfig.index];
    if (scriptConfig.scriptArray.length > scriptConfig.index) {
        if (script.trim().length > 0) {
            $.getScript(script, function () {
                console.log(script);
                SyncLoadScript({ scriptArray: scriptConfig.scriptArray, index: ++scriptConfig.index, element: scriptConfig.element }, callback);
            }).fail(function (jqXHR, textStatus, errorThrown) {
                console.log(script + " failed while loading");
                debugger;
                console.log("Error: "+errorThrown);
                SyncLoadScript({ scriptArray: scriptConfig.scriptArray, index: ++scriptConfig.index, element: scriptConfig.element }, callback);
            });         
        }
        else {
            console.log("invalid script src!!");           
        }
    }
    else {
        callback();
    }
}

Then you can make a simple call to LoadAllScripts by passing array of js file path. 然后,您可以通过传递js文件路径数组来对LoadAllScripts进行简单调用。 like below. 如下。

LoadAllScripts(["1.js","2.js","3.js","4.js"], function () {
    console.log("All the scripts have been loaded.");
    //do your stuff after all the scripts are loaded.
});

Note: I have given empty callbacks for you guys to make tweaks and pass around any data of choice. 注意:我已经为你们提供了空的回调来进行调整并传递任何选择的数据。 probably to hold all the failed scripts that you can passback to the main function and try to reload them again . probably to hold all the failed scripts that you can passback to the main function and try to reload them again

Wrote this earlier tonight, but I promise I'm not a plant. 今晚早些时候写了这个,但我保证我不是一个植物。 ;-) In addition to LabJS and RequireJS, there's also Head.js which is dead simple to use and does exactly what you want. ;-)除了LabJS和RequireJS之外,还有Head.js,它使用简单,完全符合您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM