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

前端 未结 6 527
佛祖请我去吃肉
佛祖请我去吃肉 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);
    }    
    

提交回复
热议问题