Prashobh
Prashobh

Reputation: 9542

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.

Upvotes: 2

Views: 436

Answers (4)

TPeter
TPeter

Reputation: 11

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);
}

Upvotes: 0

Phil Cooper
Phil Cooper

Reputation: 3123

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.

Upvotes: 7

CodingIntrigue
CodingIntrigue

Reputation: 78525

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);
}

Upvotes: 3

Quentin
Quentin

Reputation: 943142

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.

Upvotes: 2

Related Questions