Nate
Nate

Reputation: 28414

Are scripts added dynamically with appendChild() executed sequentially or in parallel?

I'm adding scripts to a page dynamically using code similar to this:

var s = document.createElement('script');
s.src = 'script.js';
(document.head||document.documentElement).appendChild(s);

The first script I add is jQuery bundled with a few plugins after that (all in one JS file), then the second script uses jQuery and some of the other objects created in the first JS file added.

The problem is that errors are being thrown in the second script saying jQuery, along with several other things are undefined.

I assumed scripts added to the DOM in this manner would be parsed/executed sequentially, but these errors would indicate they are executed in parallel.

Which is it?

Upvotes: 0

Views: 493

Answers (1)

php_nub_qq
php_nub_qq

Reputation: 16055

Basically you'll be advised to use a library to handle this, but I'm not a big fan of libraries since they often times offer a lot more than you need, which is not necessarily a bad thing though.

To load scripts in order you need to bind the second to load when the first one has finished loading.

var script1 = document.createElement('script');
script1.onload = function() {
    // script 1 has loaded
    var script2 = document.createElement('script');
    document.head.appendChild(script2);
    script2.src = "...";
}

document.head.appendChild(script1);
script1.src = "...";

Upvotes: 1

Related Questions