The Critical Rendering Path
You'll learn how browsers construct the DOM from HTML and when your scripts can safely interact with page elements.
How Browsers Build the DOM
When a browser receives your HTML file, it doesn't instantly display everything. Instead, it follows a precise sequence called the Critical Rendering Path:
- HTML Parsing: The browser reads HTML from top to bottom, character by character
- DOM Construction: As it parses, it builds the DOM tree node by node
- Script Encounters: When the parser hits a
<script>tag, it stops building the DOM - Script Execution: The script runs immediately (unless marked
deferorasync) - Parsing Resumes: After the script finishes, DOM construction continues
The Script Timing Problem
Imagine reading a recipe while cooking. If step 3 says "stir the mixture from step 5," you can't do it yet—step 5 hasn't happened! Similarly, if your JavaScript tries to access a DOM element that hasn't been parsed yet, it won't find anything.
<script>
// This fails! <p> hasn't been parsed yet
document.querySelector('p').textContent = 'Hello';
</script>
<p>Original text</p>
This is why scripts are often placed at the end of the <body>, or why we wait for events that signal the DOM is ready.
When Is It Safe?
The DOM is fully constructed when the browser has parsed all HTML from <html> to </html>. Only then can scripts safely access any element in the document object.
Key Takeaway: Browsers build the DOM sequentially from top to bottom; scripts execute immediately when encountered, so they can only access elements already parsed above them unless you wait for the entire document to load.