2
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.

Phil Cooper
3,1231 gold badge43 silver badges63 bronze badges
asked Nov 11, 2015 at 13:36

4 Answers 4

7

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.

answered Nov 11, 2015 at 13:39
Sign up to request clarification or add additional context in comments.

Comments

3

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);
}
answered Nov 11, 2015 at 13:39

Comments

2

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.

answered Nov 11, 2015 at 13:39

Comments

0

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);
}
answered Nov 11, 2015 at 13:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.