0

I have a doubt about the sequential order of execution of javascript in a special case, as follows. A js file (main.js) included in the head of my page sometimes needs to include another js file dynamically, like:

document.write('<script src="userdata.js"></script>');

Within this second file is defined a variable xmlFix However, if I try to reference this variable later on in main.js, it fails. Why? When is userdata.js executed?

  • http://stackoverflow.com/questions/950087/how-to-include-a-javascript-file-in-another-javascript-file for some alternative methods – Neil Neyman Dec 05 '13 at 19:18

2 Answers2

2

userdata.js would execute after the current script finished. JavaScript does go in-order, but you're making a DOM change that needs to be handled.

Brad
  • 159,648
  • 54
  • 349
  • 530
0

assuming the following code:

HTML:
<script src="a.js"></script>
<script src="b.js"></script>
a.js:
foo();
document.write('<script src="c.js"><\/script>');
bar();
b.js:
baz();
c.js:
qux();

The functions will be executed as follows:

foo();
bar();
qux();
baz();

This is because a.js needs to finish executing before the browser can move on to the next DOM element, which will be c.js, followed by b.js.

If you need code in a.js to use variables/functions defined in b.js or c.js, you will need to use a callback when the scripts have finished executing. For vanilla JS adding a callback to window.onload is a bit easier and more consistent than document.readystatechange, but the later is a little more performant.

If you're using the jQuery library, the "document ready" event is typically used (which should be along the lines of: jQuery(function ($) {...code here...});)

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Thanks, you answered my question, foresaw my follow-up question ("what if I already had a `b.js` included after `main.js`?"), and answered that too! – Mats Fjellner Dec 05 '13 at 19:52