I have been working on adding defer attribute for external scripts used in HEAD section of one of my projects. I had a query on execution order of multiple defer'ed script tags.
Below are my observation which will help us understand my query better:
As per http://www.w3.org/TR/html5/scripting-1.html
the defer attribute is present, then the script is executed when the page has finished parsing
The defer attribute does work. But, I am doubtful on the execution order. It looks like it is different on FF and Chrome.
As per my porject:
<script defer="defer" src="{SERVER_PATH}/deps.js?1441452359"></script>
<script defer="defer" src="{SERVER_PATH}/script1.js?1440067073"></script>
<script defer="defer" src="{SERVER_PATH}/script2.js?1441451916"></script>
Here, deps.js is huge file of around 120kb (gzipped), whereas, script1-3 are of regular size of 20-50kb (gzipped).
On Firefox, execution of defer'ed script does start in order of appearance, but doesn't complete in the same order. Where'as, on chrome unless the previous script completes execution, the next script's execution doesn't start. It looks like Chrome makes sense.
To test the execution order, I had inserted console.log at the first and last line of each scripts, for e.g. in deps.js
console.log("Execution Start: deps");
// minified deps script content.
console.log("Execution End: deps");
Below the console output on Firefox:
Execution Start: deps
Execution Start: script1
Execution Start: script2
// Script Error as script1 needs deps to render completely.
// Script Error as script2 needs deps to render completely.
Execution End: deps
Below the console output on Chrome:
Execution Start: deps
Execution End: deps
Execution Start: script1
Execution End: script1
Execution Start: script2
Execution End: script2
However, behavior on FF is not always as shown above. Sometimes it does work like Chrome. It look like an issue which is Firefox only. Or, may be is it because of the deps.js file being heavy and minified and takes time to render.
Can anyone of similar experience with defer help me? Please let me know, if any other information is needed.
PS: Other solutions like, moving the scripts at the bottom of the page is not something I am looking at this moment.
A B C
in wrong order? – Pretoria