Web Development · Module 1 · Lesson 21 min read

How a Browser Renders a Page

From bytes to pixels

When HTML arrives, the browser goes through the critical rendering path:

  1. Parse HTML → build the DOM (Document Object Model), a tree of elements.
  2. Parse CSS → build the CSSOM (the styles for each element).
  3. Combine them into the render tree (only visible elements).
  4. Layout (reflow): calculate the size and position of each box.
  5. Paint: fill in pixels (text, colours, images).
  6. Composite: stack layers and show them on screen.

Where JavaScript fits

  • A normal <script> blocks HTML parsing while it downloads and runs.
  • <script defer> downloads in parallel and runs after the HTML is parsed, in order. Use it for most scripts.
  • <script async> runs as soon as it's downloaded, in any order. Good for independent scripts like analytics.

Why it matters

  • Large CSS and blocking scripts delay the first paint.
  • Changing layout properties (width, top, font size) triggers reflow, which is expensive. Animating transform and opacity is cheap.
  • Put CSS in <head> and scripts at the end of <body> or use defer.

The DOM is live

JavaScript can read and change the DOM at any time (document.querySelector, element.textContent), and the page updates immediately. That's how interactive websites work.

Example

HTML
<!DOCTYPE html>
<html>
  <head>
    <title>Render demo</title>
    <style> p { color: #4f46e5; } </style>
    <!-- defer: runs after the HTML is parsed -->
    <script defer>
      document.querySelector("#msg").textContent = "Changed by JavaScript ✨";
    </script>
  </head>
  <body>
    <h1>Hello, DOM</h1>
    <p id="msg">Original text</p>
  </body>
</html>
<!-- ▶️ Paste into the code editor's HTML mode and tap Run -->