Upon defer attribute MDN says:
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. The defer attribute should only be used on external scripts.
On DOMContentLoaded
MDN also says:
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets...
So DOMContentLoaded
is fired before CSSOM
is ready. This means deferred scripts are executed before CSSOM
is ready. But if that's true the scrips must not be able to get correct CSS property values and must not apply CSS correctly. But it's not true, we know all deferred scripts work well.
- So is MDN documentation technically incorrect?
- Where can I find the official documentation of DOMContentLoaded`? I searched in https://dom.spec.whatwg.org/ but couldn't find it.
P.S: Please note that google says that CSSOM is built before executing any inline javascript
But Google is technically incorrect. Inline JavaScript gets executed before CSSOM is ready. And from my tests, I found that MDN is correct and if js files(both deferred and non-deferred) are downloaded before CSS files(or js is inline) then js is executed before CSSOM is ready. So js might handle styles incorrectly. To avoid that we need a forced reflow before all js logic.
So if a user visits our website with all js required already cached and CSS not cached OR js gets downloaded before CSS then (s)he might see an incorrectly rendered page. To avoid this we should add force reflow in all our websites' js files.