External Javascript loading and execution in <head>

I have a hard time finding a definite specification to explains the expected behavior for javascript execution vs. downloading order in the head.

The html 5 semantics specification on the w3c site doesn’t make any distinction for the script tag whether in the head or body but browsers do behave differently for both cases.

Scripts are downloaded in parallel in the head, therefore there is a wonder to whether the execution of the code in the libraries is affected by the loading.
Btw, I am not talking about trying any DOM writing (not in head), but something that could be as simple as defining variables or classes (where a variable would be created in one JS library and used to create another one in another JS library for instance) That happens if you load a 3rd party library that defines elements that you use to declare your own elements in your own library.

Typically for

<head>
<script type=“text/javascript” src=“script1.js”></script>
<script type=“text/javascript” src=“script2.js”></script>
<script type=“text/javascript” src=“script3.js”></script>
<script type=“text/javascript” src=“script4.js”></script>
</head>

the loading order can be

script1.js
script3.js
script4.js
script2.js

However it would seems to me that because we are in the <head> and because the page didn’t start to render yet, it would make sense to wait until the closing of the head to execute the javascript.

It seems that this is confirmed by adding alert statements in the JS files.
The order in which the alerts are popping up is the same as the order in which the files are declared, plus the alerts starts to appear only after the last file in the header is downloaded.
However my observations can be subjective, plus could not a guarantied behavior through all browsers unless this is understood to be the way they are meant to behave.

Does anybody have some insights on that?

Thanks.

All browsers behave like this. They execute JavaScripts in the order they appear. Tens of thousands of websites successfully rely on this fact.

Thanks for your reply. Browser indeed execute javascript in the order they appear by default. In the <body> javascript downloading is serialized, however the execution order can be affected by the use of the defer attribute.
However I was looking for data about the <head>. It seems to me that all the scripts execution is ‘deferred’ in the <head> therefore it guaranties order. It HAS TO be working that way due to the use of libraries such as prototype or jquery that would be have to have been loaded before any other library using their capabilities can be loaded.
I was just surprised to see such level of details on W3C for the script tag which by the way it is written appears to be targeted for the behavior in <body>.
May be indeed the need for the execution order to be preserved in the <head> is so obvious that it doesn’t have to be specified anywhere :slight_smile: