Upon defer attirbute 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 thats 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 not that google says that CSSOM is build before executing any inline javscript
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 force 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 incorrectly rendered page. To avoid this we should add force reflow in all our websites' js files.
I didn't really read the spec though. The following are based on actual behaviors of Chrome (observed on Chromium 68, Ubuntu). Behaviors may vary among browsers, if they were just undefined in specifications. For example in 2010 scripts don't always wait for proceeding stylesheets. I assume agreements had been achieved and behaviors had been standardized over the years.
The
defer
scripts are executed afterdomInteractive
, beforedomContentLoaded
; it's sequential.domInteractive
anddomContentLoaded
are two timestamps which could be viewed in Chrome devtools' Performance (previously Timeline) tab. Probably also in other similar tools, but I haven't tried.domInteractive
is the point when HTML parsing and initial DOM construction are finished (and all "sync" scripts have finished executing).document.readyState
changes from'loading'
to'interactive'
; areadystatechange
event fires ondocument
accordingly.All
defer
scripts are executed in their appearing order. Then comesdomContentLoaded
, aDOMContentLoaded
event fires ondocument
.DOM & CSSOM construction don't rely on each other; but sync scripts may introduce dependencies.
Each sync script, internal or external, waits for preceding stylesheets to be parsed (of course, after fetched).
Yes, sync scripts are not blocked by subsequent stylesheets. MDN and Google and other articles say "scripts depend on CSSOM to be ready"; they (probably) didn't mention that only preceding parts are depended.
Google didn't say that (at least, as of the time I read this article).
On the contrary, before one sync script is fetched (if external) and executed, any code following it, HTML, stylesheets or other scripts, can't be parsed/executed/constructed. They block anything subsequent to them.
So, in specific cases, eg. without sync scripts,
DOMContentLoaded
event may fire before or after CSSOM is ready. That's what MDN means by saying "without waiting for stylesheets".defer
/async
scripts don't care about stylesheets at all.Different from sync scripts,
defer
/async
scripts don't wait for preceding stylesheets, and don't block subsequent stylesheets/scripts either. They are removed from those "dependency chains" completely. You can't rely on any proceeding stylesheets to have been parsed.The differences between
defer
/async
:defer
scripts have predictable execution time; the DOM has been ready. They are also promised to execute in order.async
scripts have no promise on execution order; eachasync
script would be "queued to execute" as soon as it is fetched; once the render process is idle, they are executed. (To be exact, different types of resources have different priorities. The spec provides precious requirements)These should well explain hinok's two examples, the former
async
(from Google) and the latterdefer
。I don't have much experience on working with CSSOM at page loading (I do operate on DOM at page loading, though), so I can't provide reliable advises. It seems "
load
event onwindow
" or "force reflow early" might work.DOMContentLoaded
can be fired before CSSOM, sourceArticle on Google Developer describes
async
instead ofdefer
but in the case of your question, it doesn't change anything because based on Steve Sourders article on perfplanetand his comment under his article
You can make your own experiment, look below for code using
defer
and timelineI use deferred script loading. There was a lengthy technical explanation from some guy who is a well known website performance guru. He clearly states that deferred is the way to go (for this and that technical reason, backed by all kinds of data and charts, that many people seemed to feel was wide open for debate, re: async).
So I started working with it. Deferred scripts have the advantage of downloading async, but executing in the order presented, which can be a problem with async (e.g. you can load your app bundle before your vendor bundle because you don't control the execution order of async scripts just by saying "in this order").
However, I found out right away that although this solves that problem, this could mean, depending on how you grab your bundles, the CSS bundle isn't loaded. So you can end up with unstyled content, depending on how you set things up. Note that for defer, they also say that you shouldn't be writing to the dom etc. in those scripts (which again makes sense in terms of your documentation).
So it would seem your documentation is correct. The effect is easily reproduced.
How do I get out of it; the most basic way, is like this:
This makes sure that the css loads in first, so your home page and so on will show up nicely, and also ensures that (although all three are loading async), that app.bundle will execute last, ensuring all other dependencies are in order.
So, you take the absolute bare minimum of CSS required to kick over the app, create that as a bundle, and load it first, before anything. Otherwise you can bundle in your CSS per module/component, and so on.
There's a lot more to this topic and I could probably be doing more, but again (I will try to find the reference), this was overtly recommended by that performance wizard, so I tried it and it seems pretty effective to me.
Edit: Fascinating, while looking for that reference (which I haven't found yet), I went through a handful of "experts" on the subject. The recommendations differ wildly. Some say async is far superior in all regards, some say defer. The jury really seems out on the topic, overall I'd say it probably has more to do with exactly how you build out your scripts than whether one is actually better than the other.
Edit again: Here's some more evidence. I ran a performance analyzer on a stub website using the above simple loading sequence, deliberately making the scripts naive so they'd be visible in a timeline.
Here's an SS of the result: there are four yellow boxes here. The first three are the evaluations of the scripts. The fourth one (when you mouse over it in the tool, this is just the SS remember) is the DOMContentLoaded event (the one with the red corner).