简体   繁体   中英

Loading .js files using javascript in synchronous manner

I need to include multiple js files in synchronous manner and once they are successfully included I will call function main() which will create the widget. For that currently I have built a function this way

var scriptArrayHC = [retrieveURL()+"/js/bootstrap.min.js",
                    "//platform.twitter.com/widgets.js",
                    retrieveURL()+"/js/html5shiv-2.js",
                    retrieveURL()+"/js/ie-emulation-modes-warning.js",
                    retrieveURL()+"/js/ie10-viewport-bug-workaround.js"];
function loadScript(scriptArray, func){
    var counter_script=0;
    [].forEach.call(scriptArray, function(src){
        var script = document.createElement('script');
        script.onload = function() {
            counter_script++;
            //console.log("Script "+counter_script+" --- "+src);
            if(counter_script==scriptArray.length) eval(func);
        };
        script.src = src;
        document.getElementsByTagName('head')[0].appendChild(script);
    });
}

loadScript(scriptArray, "main()");

It is working fine.. But i think it is not the best way. Does anyone have a better way to do this or is there any library for this?

使用RequireJS解决问题

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