The external script deferred by the defer
attribute is executed before the (DOMContentLoaded) is fired, i.e. when the initial HTML document has been completely loaded and parsed. The onLoad
attribute on a <body>
tag, on the other hand, fires only when a web page is fully loaded.
Therefore, the defer attribute is indeed working. You may test it by trying the two cases below. In both cases the content of script.js file should be this:
console.log(document.getElementById('sample').innerHTML);
CASE 1 HTML - with defer
--> logs "Sample text"
<body onLoad="elem_onload()">
<script type="text/javascript" src="script.js" defer></script>
<div id="sample">Sample text</div>
</body>
CASE 2 HTML - without defer
--> logs an error
<body onLoad="elem_onload()">
<script type="text/javascript" src="script.js"></script>
<div id="sample">Sample text</div>
</body>
Thx. all for help.
So the statement "...after the document has been parsed" from original doc. (MDN <script> tag) refers say step #0 from 12.2.6 The end
when document is completely parsed and now there are several tasks to be done on that occasion. Those tasks includes running external deferred scripts which
is prior (#3) to onload
event.
Am I right?