CSSOM & Parsing
Overview
When the browser downloads an HTML file, it builds the DOM (Document Object Model). But when it encounters a CSS file, it parses those styles into a completely separate tree called the CSSOM (CSS Object Model). The browser then merges the DOM and the CSSOM together to form the 'Render Tree', which determines exactly what gets painted to the user's screen. Because the browser cannot draw the page without the CSSOM, CSS is inherently 'Render Blocking'.
Syntax
/*
Browser encounters this CSS file.
It maps these styles to the CSSOM node for 'div' and 'span'.
*/
div {
background-color: black;
}
div span {
color: white;
}Common Pitfalls
- Placing your
<link rel="stylesheet">tags at the bottom of the HTML document. This is catastrophic for performance. The browser will render the unstyled raw HTML (creating an ugly flash of unstyled content - FOUC), and then suddenly redraw the entire page once the CSS loads. - Using
@importinside your CSS files to load other CSS files. This forces the browser to download files sequentially rather than in parallel, heavily delaying the creation of the CSSOM and killing page load speeds.
Interview Questions
The browser refuses to paint any pixels to the screen until it has completely downloaded and parsed all CSS files to construct the CSSOM. If it painted the HTML first, the screen would violently flash and shift as the CSS was applied moments later.
Real-World Example
How JavaScript interacts dynamically with the CSSOM.
// JS can read and manipulate the CSSOM directly in real-time
const box = document.querySelector('.box');
// This updates the CSSOM node, forcing the browser to instantly repaint
box.style.backgroundColor = 'blue';Check Your Knowledge
Test your understanding of CSSOM & Parsing with these quick questions.