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.

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.

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

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.

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

Comments

Your Answer

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.