How Does the Browser Render HTML?


First published: 15/08/2024

The browser goes through a whole pipeline of actions to render your HTML.

The rendering pipeline for displaying HTML to the browser.

Construction

The browser starts by parsing the HTML + CSS and constructs the Document Object Model (DOM) and the CSS Object Model (CSSOM). These objects represent the structure and style of a given web page.

These two objects are then merged into the render tree, which represents all of the elements that will be rendered to the document, including the styles applied to each HTML element.

Layout / Reflow

Once that’s done, the browsers determines the dimensions and positions of these elements on the screen. This is a process known as layout. Layout is a CPU-intensive operation that can be affected by all manner of things like:

  • the depth of the DOM
  • the size of the DOM
  • the complexity of CSS selectors
  • the number of CSS rules

While layout happens on the first render of the page. The browser can perform reflow, which is a similar process that happens on subsequent alterations to the page’s structure. It can occur after:

  • adding or removing an element to the DOM
  • applying certain styles to an element, like height and width
  • using JavaScript to ready and modify the DOM

The browser may not run the reflow for the entire DOM tree, but a subtree depending on where in the DOM tree the change was.

Paint / Repaint

Paint happens on the first render of the page and repaint occurs after subsequent reflows. This is when the browser displays the visual content to the screen.

It’s worth noting that there are CSS properties that you can apply to your HTML after initial render that don’t trigger a reflow. Understanding how to avoid reflow can be hugely helpful when trying to optimise your web page for performance. Properties that don’t affect the flow of the DOM include:

  • color and backgroundColor
  • visibility
  • outline
  • …and others

Wrapping Up

In a previous edition of the newsletter, I talked about using document fragments to batch write changes to the DOM to reduce reflows. Having a high-level overview of how the browser renders your HTML can help you spot possible performance bottlenecks and fix them, so it’s worth diving deeper if you’d like to learn more:

Additional Resources



If you enjoyed this article, then I figure you like to be kept in the loop with web development tips. If so, the Component Odyssey newsletter might be right up your alley.