Sobes.tech
Middle+

How does a browser parse an HTML file?

sobes.tech AI

Answer from AI

The browser reads the HTML file byte by byte. Based on the file encoding, a stream of characters is constructed. This stream is parsed, forming tokens (opening and closing tags, text, comments, doctype). Tokens are converted into nodes, which are linked into a tree — the Document Object Model (DOM).

The parsing process involves the following stages:

  1. Reading bytes: The browser receives a stream of bytes.
  2. Determining encoding: The file encoding is determined (e.g., UTF-8, Windows-1251). This can happen through HTTP headers, <meta> tags, or automatically.
  3. Converting to characters: Bytes are converted into characters according to the specified encoding.
  4. Tokenization: The character stream is split into tokens.
    <!-- Example tokens -->
    <p> // Token: opening tag "p"
      Hello, // Token: text "Hello, "
      world! // Token: text "world!"
    </p> // Token: closing tag "p"
    
  5. Building the AST (DOM Tree): Based on the sequence of tokens, a tree of nodes (DOM) is constructed. The browser maintains a stack of open tags; when it encounters a closing tag, it closes the corresponding open tag from the stack and adds its node to the tree.
    <!-- Simple DOM structure for: -->
    <!DOCTYPE html>
    <html>
      <head>
        <title>Example</title>
      </head>
      <body>
        <p>Text</p>
      </body>
    </html>
    
    // The DOM tree will have a structure reflecting the nesting of tags.
    // For example, the "p" node will be a child of the "body" node.
    
  6. Parsing scripts and styles: During HTML parsing, the browser encounters <script> and <link>/<style> tags.
    • <script>: By default, HTML parsing is paused when a <script> tag is encountered, the script is loaded, parsed, and executed. After execution, parsing resumes. The async and defer attributes modify this behavior. async executes the script asynchronously, not blocking parsing. defer delays script execution until after HTML parsing is complete.
    • <link> / <style>: CSS is parsed in parallel with HTML and creates a CSS Object Model (CSSOM). The presence of <link> before <script> can delay script execution, as the browser may wait for CSSOM construction to ensure correct style application before executing scripts.