Reputation: 9542
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
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
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
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
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