Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 793
Nikita Avatar asked Jul 12 '10 19:07

Nikita


People also ask

In what order are script tags executed?

It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.

Does the order of script tags matter?

No, you should always load Javascript in the order that it's needed. If you're using some jQuery plugins, then you should load jQuery before those plugins, as they may instantiate something that uses the jQuery object(s) without you knowing.

Do script tags load in order?

Script tags are executed in the order they appear It also means scripts which appear later on the page can depend on things scripts which appear earlier have done. Elements on the page won't render until all the script tags preceding them have loaded and executed.

Which of the following is executed first by a browser?

The browser loads the html (DOM) at first. The browser starts to load the external resources from top to bottom, line by line.


1 Answers

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:

  • triggering asynchronous processing through your own code (not in this example)
  • adding script tags dynamically
  • using the defer attribute.
like image 117
ChristopheD Avatar answered Sep 22 '22 04:09

ChristopheD