Render-tree Construction, Layout, and Paint
- The DOM and CSSOM trees are combined to form the render tree.
- Render tree contains only the nodes required to render the page.
- Layout computes the exact position and size of each object.
- Paint is the last step that takes in the final render tree and renders the pixels to the screen.
The Render Tree Algorithm
- Starting at the root of the DOM tree, traverse each visible node.
- Some nodes are not visible at all (e.g. script tags, meta tags, and so on), and are omitted since they are not reflected in the rendered output.
- Some nodes are hidden via CSS and are also omitted from the render tree - e.g. the span node in example above is missing from the render tree because we have an explicit rule that sets “display: none” property on it.
- For each visible node find the appropriate matching CSSOM rules and apply them.
- Emit visible nodes with content and their computed styles.
The Layout Stage
Also knows as "reflow". It's the part where the browser calculates the exact position and size within the viewport of the device.
Let's consider a simple hands-on example:
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Critical Path: Hello world!</title>
</head>
<body>
<div style="width: 50%">
<div style="width: 50%">Hello world</div>
</div>
</body>
</html>
The output of the layout process is a “box model” which precisely captures the exact position and size of each element within the viewport.
Let’s examine the layout stage for our original “hello world” example:
- The render tree construction and position and size calculation are captured with the “Layout” event in the Timeline.
- Once layout is complete, the browser issues a “Paint Setup” and “Paint” events which convert the render tree to actual pixels on the screen.
Recap
- Process HTML markup and build the DOM tree.
- Process CSS markup and build the CSSOM tree.
- Combine the DOM and CSSOM into a render tree.
- Run layout on the render tree to compute geometry of each node.
- Paint the individual nodes to the screen.
Optimizing the critical rendering path is the process of minimizing the total amount of time spent in steps 1 through 5 in the above sequence.