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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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!

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.