The defer attribute allows a classic external script to download while HTML parsing continues. The script executes after parsing finishes and before the DOMContentLoaded event, subject to normal script-loading rules.
Some script types, including module scripts, have their own loading and execution rules. You will study JavaScript loading in more detail in the appropriate course.
11. How Browsers Parse HTML
HTML parsing is the process by which a browser converts HTML source text into a structured document.
Browsers do not simply display every source character literally. They interpret markup according to HTML parsing rules.
Step 1: Receive HTML
The browser receives HTML as part of a response or reads it from a local file.
Step 2: Tokenization
The HTML parser processes the input and identifies tokens representing start tags, end tags, text, comments and other constructs.
Step 3: Tree Construction
The parser uses these tokens and HTML parsing rules to build the document tree.
Step 4: DOM Creation
The resulting structure is represented through the Document Object Model (DOM), which scripts and browser features can access.
Step 5: Rendering
The browser combines the document structure with styles, resources and other processing to calculate layout and display the page.
These stages describe the general process. Browser loading and rendering can overlap, and the DOM may change as scripts execute.
12. HTML Source vs DOM
The HTML source is the markup supplied to the browser. The DOM is the structured document representation created by the parser and potentially modified later by scripts.
They are related, but they are not always identical.
Example: Browser-Generated Structure
<table>
<tr>
<td>HTML</td>
</tr>
</table>When parsing a table, the browser can insert an implicit tbody element into the DOM, even if the source does not explicitly contain one.
This is an example of HTML parser tree construction. The browser follows HTML parsing rules rather than treating the source as an arbitrary XML document.