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

前端 未结 6 431
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 20:10

I need to load a variable number of javascript source files before running javascript code that depends on them. Sometimes 1 script needs to be loaded, other times 2. The ge

相关标签:
6条回答
  • 2021-01-12 20:18

    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);
    }    
    
    0 讨论(0)
  • 2021-01-12 20:27

    I suggest you look into LABjs

    That is exactly what its purpose is.

    0 讨论(0)
  • 2021-01-12 20:27

    Loading multiple scripts by $.getScript() one after the other and do stuff after all the scripts are loaded

    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. 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

     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. 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.

    0 讨论(0)
  • 2021-01-12 20:40

    I've use RequireJS quite extensively and it's very good. 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. 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.

    0 讨论(0)
  • 2021-01-12 20:41

    If you are using jquery 1.5 you can use the new deferred syntax.

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

    Just pass in the scripts you wish to load.

    0 讨论(0)
  • 2021-01-12 20:43

    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.

    0 讨论(0)
提交回复
热议问题