简体   繁体   中英

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

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

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

That is exactly what its purpose is.

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.

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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