How a Browser Renders a Page
From bytes to pixels
When HTML arrives, the browser goes through the critical rendering path:
- Parse HTML → build the DOM (Document Object Model), a tree of elements.
- Parse CSS → build the CSSOM (the styles for each element).
- Combine them into the render tree (only visible elements).
- Layout (reflow): calculate the size and position of each box.
- Paint: fill in pixels (text, colours, images).
- 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
transformandopacityis cheap. - Put CSS in
<head>and scripts at the end of<body>or usedefer.
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
<!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 -->