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

前端 未结 6 442
佛祖请我去吃肉
佛祖请我去吃肉 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: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.

提交回复
热议问题