Nikita
Nikita

Reputation: 6079

Order of JavaScript <script> tag executions not guaranteed in major browsers?

Is it true that there are no guarantees across major browsers that the following script tags will always execute both sequentially AND in order of declaration? i.e. should I assume that the following code will not always yield x == 'ab' in alert?

<head>
    <script type="text/javascript">
      //tag A
      var x = x || ''; x += 'a';
    </script>
    <script type="text/javascript">
      //tag B
      var x = x || ''; x += 'b';
    </script>
</head>
<body>
    <script type="text/javascript">
       alert('x='+x);
    <script>
</body>

... and it's possible that x will instead be one of the following:

  1. 'ba' - if tag B executes before A
  2. 'a' or 'b' - race condition where A and B execute in parallel (Though seems like this thread clearly says that browsers only allocate a single thread of JS)

Upvotes: 29

Views: 19488

Answers (1)

ChristopheD
ChristopheD

Reputation: 116117

The execution order of these non-dynamically added script tags should be purely sequentially in every browser:

Snippet from this link:

JavaScript statements that appear between <script> and </script> tags are executed in order of appearance; when more than one script appears in a file, the scripts are executed in the order in which they appear.

However, things could change as soon as you're:

Upvotes: 35

Related Questions