htmlcssdomwebcssom

Is CSSOM and DOM creation asynchronous?


I have read that CSSOM creation is a bottleneck in terms of web page performance. But there seems to be some ways around it, like adding the media property to the stylesheet link. I'm trying to understand how to optimise my web app and came across this really interesting link but couldn't understand what order CSSOM and DOM creation happen in.

Here I see some reference to asynchronous loading of CSS files, but the answer is not very clear. Of course, that is about loading and not object model creation.

My question is this: Does the CSSOM creation and DOM creation happen in parallel or in sequence?


Solution

  • Yes, the CSSOM and DOM creation happens asynchronously and it is only logical. I would recommend you start off at Google Web fundamentals where topics like rendering are discussed and explained in depth.

    1. DOM Construction starts as soon as the browser receives a webpage from a network request or reads it off the disk. It starts "parsing" the html and "tokenizing" it, creating a DOM tree of nodes that we are aware of.

    2. While parsing and constructing the DOM tree, if it encounters a link tag in the head or any other section for that matter, referencing an external stylesheet. (from the docs)

    Anticipating that it will need this resource to render the page, it immediately dispatches a request for this resource,...

    1. The CSS rules are again tokenized and start forming what we call a CSSOM. The CSSOM tree is then generated finally as the entire webpage is parsed and then applied to the nodes in DOM tree.

    When computing the final set of styles for any object on the page, the browser starts with the most general rule applicable to that node (e.g. if it is a child of body element, then all body styles apply) and then recursively refines the computed styles by applying more specific rules - i.e. the rules “cascade down”.

    We have all noticed that on slow connections, the DOM loads first and then styles are applied and webpage looks finished. It is because of this fundamental reason - The CSSOM and DOM are independent data structures.

    I hope it answers your question and points you in the right direction.

    PS: I would strongly recommend again, to read through Google web performance fundamentals to gain better insights.