简体   繁体   中英

Dynamically load javascript files

var _scriptUrl = [
    'vendor/jquery/jquery-1.9.1.min.js',
    'vendor/angular/angular.js',
    'vendor/angular/angular-cookies.js',
    'vendor/bootstrap/js/bootstrap.min.js',
    'vendor/bootstrap/js/bootstrap-datepicker.js'
]

var jsElm = document.createElement("script");
jsElm.type = "application/javascript";

for(var i = 0; i < _scriptUrl.length; i++)
{
    jsElm.src = _scriptUrl[i];
    document.body.appendChild(jsElm);
}

But it is always appending last one only, please suggest.

Try appending the child in the loop. In your example, you only have one instance of script.

for(var i = 0; i<_scriptUrl.length; i++)
{
    var jsElm = document.createElement("script");
    jsElm.type = "application/javascript";
    jsElm.src = _scriptUrl[i];
    document.body.appendChild(jsElm);
}

If you're serious about async loading of js, try requirejs .

You're declaring the jsElm outside of your for loop, therefore referencing the same element on each iteration. Move this declaration inside your for loop:

var _scriptUrl = [
    'vendor/jquery/jquery-1.9.1.min.js',
    'vendor/angular/angular.js',
    'vendor/angular/angular-cookies.js',
    'vendor/bootstrap/js/bootstrap.min.js',
    'vendor/bootstrap/js/bootstrap-datepicker.js'
]

for (var i = 0; i < _scriptUrl.length; i++) {
    var jsElm = document.createElement("script");
    jsElm.type = "application/javascript";
    jsElm.src = _scriptUrl[i];
    document.body.appendChild(jsElm);
}

You are creating a single <script> and then changing its src rapidly so that only the last one has enough time to load.

Create the script element inside the loop.

You are always update the jsElm.src .

for(var i= 0;i<_scriptUrl.length;i++)
{
    var jsElm = document.createElement("script");
    jsElm.type = "application/javascript";
    jsElm.src = _scriptUrl[i];
    document.body.appendChild(jsElm);
}

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