1

If I have an HTML page embedding several <script> tags, is there a guarantee that these script files will be executed in order they appear in the HTML file?

For example:

<script src="script1"></script>
<script src="script2"></script>

Is it guaranteed that script1 will always be executed before script2? If so, is it a cross-browser standard?

4
  • 2
    They will be parsed and interpreted in the order you have included them.. Commented Mar 25, 2016 at 10:00
  • 1
    Is it guaranteed that script1 will always be executed before script2? YES, the script are loaded synchronously. That means they execute one after the other. Commented Mar 25, 2016 at 10:03
  • Keep in mind that if you have a ajax call in the first one, the second script will not wait for the call to be done Commented Mar 25, 2016 at 10:04
  • 1
    In supporting browsers you may set the async attribute. It defaults to false => synchronous. Commented Mar 25, 2016 at 10:06

2 Answers 2

2

The answer is yes. The browser will download both scripts in parallel and execute them as soon as possible, maintaining their order. Here's a handfull article that treats this subject.

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

1 Comment

Nice. BTW I found the standard here if it's helpful to other people: w3.org/TR/html5/scripting-1.html#attr-script-async
0

Those JS files will be parsed and interpreted by browser in the order you putted them : script1.js, then script2.js.

However, it doesn't garanty that the code in script1.js will be executed before script2.js : it depends on the code.

For example, let's consider you are listening to a DOM ready event in script2.js and you are listening to an image loaded event in script1.js. In this case, the code in script2.js will be parsed and interpreted after the code in script1.js, but it will be executed after.

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.