Skip to content

How Browsers Work ​

A browser is a program that fetches the resources a user asks for (HTML, CSS, images, and so on) from a server, interprets them by a fixed set of rules, and draws them on the screen. From the moment you type https://naver.com into the address bar and press Enter until the page appears, the browser keeps running a "fetch → interpret → draw" cycle.

At a Glance ​

  • A browser does two main jobs.
    1. Networking: it finds the server and fetches documents and files.
    2. Rendering: it interprets the fetched HTML and CSS and turns them into a visible screen.
  • Analogy: a browser is like a construction company that receives blueprints and builds a house.
    • HTML is the structural blueprint that says "how many rooms there are and what goes where".
    • CSS is the interior design sheet that says "what color the wallpaper is and how big the windows are".
    • The rendering engine is the construction crew that combines the two documents and actually builds the house.
    • The crew starts building with the parts it has, even before the whole blueprint arrives. That is why a web page does not appear all at once but fills in little by little from the top.

The big flow from the rendering engine receiving HTML to drawing it on screen has the four steps below. Each step is covered in detail in How Rendering Works.

The basic flow of a rendering engine: parsing HTML to build the DOM tree, building the render tree, laying out the render tree, painting the render tree

Image source: NAVER D2, How Browsers Work

Main Functions of a Browser ​

The main function of a browser is to request the resource the user chose from a server and display the received resource in the browser window.

  • Resources come in many forms, such as HTML documents, PDFs, and images.
  • The location of a resource is given by a URI (Uniform Resource Identifier). The URL we type into the address bar is one kind of URI.
  • The browser interprets and displays documents according to the HTML and CSS specifications (standard rules).
    • Today the HTML specification is maintained by WHATWG, a group of browser vendors, under the name "HTML Living Standard", and the CSS specification is defined by the web standards body W3C (World Wide Web Consortium).
    • Older browsers followed only part of the specifications and extended features in their own ways. This led to serious compatibility problems like "this site looks right only in a specific browser". Today most browsers follow the standard specifications.

Browsers look a little different from each other, but by copying each other's good features, they now share almost all of the elements below.

  • An address bar for entering URIs
  • Back / forward buttons
  • Bookmarks (favorites)
  • Refresh / stop buttons
  • A home button

Basic Structure of a Browser ​

You can think of a browser as seven parts with different roles.

User Interface
   │
   ▼
Browser Engine ─────▶ Data Storage
   │
   ▼
Rendering Engine
   ├──▶ Networking
   ├──▶ JavaScript Interpreter
   └──▶ UI Backend

Main components of a browser: user interface, browser engine, rendering engine, networking, JavaScript interpreter, UI backend, data storage

Image source: NAVER D2, How Browsers Work

ComponentWhat it does
User interfaceThe parts the user touches directly, such as the address bar, back/forward buttons, and bookmarks. It is everything except the window that shows the requested page.
Browser engineA middle manager that controls actions between the user interface and the rendering engine.
Rendering engineDisplays the requested content on screen. When you request HTML, it parses the HTML and CSS and draws them on screen.
NetworkingHandles network calls such as HTTP requests. It is a platform-independent interface that hides the parts that differ between operating systems.
UI backendDraws basic widgets such as combo boxes and windows. The actual drawing borrows the operating system's user interface features.
JavaScript interpreterInterprets and runs JavaScript code. Chrome's V8, Firefox's SpiderMonkey, and Safari's JavaScriptCore are well-known examples.
Data storageThe layer where the browser stores data on disk, such as cookies, localStorage, and IndexedDB.

Note: Chrome runs a separate rendering engine process for each tab. That is why the other tabs keep working when one tab freezes. What a process is is covered in Processes and Threads.

The Big Flow from Typing a URL to Showing the Screen ​

This is the whole flow behind the classic interview question "What happens when you type a URL into the address bar?". Before the rendering engine starts working, there is a networking stage first.

① Parse URL       https://naver.com  →  protocol(https) + domain(naver.com) + path(/)
      │
② DNS lookup      naver.com  →  IP address (e.g. 223.130.x.x)
      │
③ TCP connection  3-way handshake (SYN → SYN+ACK → ACK)
      │
④ TLS connection  for https, exchange encryption keys (check the certificate)
      │
⑤ HTTP request    GET / HTTP/1.1  Host: naver.com
      │
⑥ HTTP response   200 OK + HTML document
      │
⑦ Rendering       parse HTML → parse CSS → render tree → layout → paint → composite
      │
⑧ More requests   request and fetch the CSS, JS, and image files referenced in the HTML
StepIn plain words
Parse URLSplits the address into "by what method, to which house, to which unit". If it is a search term rather than an address, it is sent to the search engine.
DNS lookupTurns the human-readable name (naver.com) into the phone number computers use (an IP address). It looks in the browser cache, the OS cache (including the hosts file), and then DNS servers, in that order.
TCP connectionSets up a "phone call" with the server. It is called a 3-way handshake because both sides check three times that they can hear each other.
TLS connectionAgrees on encryption so that no one can eavesdrop on the call. This happens only when the address starts with https.
HTTP request / responseYou ask "please give me this page", and the server returns the HTML with a status code. For details, see HTTP Request Methods and HTTP Status Codes.
RenderingInterprets the received HTML and draws the screen. This is explained in detail below.

What Is Rendering? ​

Rendering is the process of turning text-based code such as HTML, CSS, and JavaScript into a screen (pixels) the user can see. The part that does this job is the rendering engine.

  • By default, a rendering engine can display HTML and XML documents and images.
  • Other formats such as PDF are displayed with a viewer built into the browser or with an extension (plug-in).

Types of Rendering Engines ​

BrowserRendering engineNotes
Chrome, Edge, Opera, Samsung InternetBlinkAn engine Google forked from WebKit in 2013. Edge has used Blink since 2020.
SafariWebKitIt started when Apple took KHTML, an open-source engine for Linux, and adapted it for Safari on Mac and Windows.
FirefoxGeckoAn engine made by the Mozilla Foundation.

On iPhone and iPad, because of App Store rules, even Chrome and Firefox have used WebKit internally. (Since 2024, other engines are allowed only in the European Union.) So if "the page breaks only in Chrome on iPhone", it is most likely a Safari problem.

How Rendering Works ​

The basic flow of a rendering engine is as follows.

  1. It parses the HTML, turns every tag into a DOM node, and builds a DOM tree (content tree) from these nodes.
  2. It parses external CSS files and the styles inside style tags to build the CSSOM (style rule tree).
  3. It combines the DOM and the style information into another tree called the render tree. The render tree contains rectangles with visual properties such as color and size, in the order they will be shown on screen.
  4. Layout: it calculates exactly where on the screen each node of the render tree goes and how big it is.
  5. Paint: it walks the render tree using the UI backend and paints each node as actual pixels.
 HTML ──parse──▶ DOM tree ──┐
                            ├──attachment──▶ render tree ──▶ layout ──▶ paint ──▶ screen
 CSS  ──parse──▶ CSSOM    ──┘

The important point is that this process runs progressively. To show the user something as quickly as possible, the rendering engine does not wait until it has received all of the HTML. It starts layout and painting with the parts it has already received. That is exactly why a web page fills in gradually instead of appearing all at once.

What Is the DOM? ​

DOM (Document Object Model) is a tree-structured object model that the browser builds to understand and work with an HTML document.

  • If you look at a web page's source, you see tags like <html> and <body>. Turning these tags into objects that JavaScript can work with gives you document objects.
  • "Model" means the structure that defines how these objects relate to each other (parent, child, sibling).
  • In short, the DOM is the way a web browser recognizes an HTML page, and it is a tree.
  • The DOM is also why JavaScript can find an element with document.querySelector('h1') and change its text. This site's Dark Mode also works by changing attributes of DOM elements.

WebKit's Structure and Attachment ​

WebKit calls the flow above by the following names.

General termName in WebKit
Render treeRender Tree (render objects are called renderers)
LayoutLayout
Building the render treeAttachment

As in the figure below, the DOM tree built by the HTML parser and the style rules built by the CSS parser meet at attachment and become the render tree.

How WebKit works: the results of the HTML parser and CSS parser go through attachment to become the render tree, then through layout and painting to appear on screen

Image source: NAVER D2, How Browsers Work

Attachment: the process in which WebKit connects DOM nodes with style information to build the render tree.

Firefox (Gecko) calls the same process by different names. It calls the render tree the Frame Tree, layout Reflow, and attachment Frame Construction. Only the names differ; the flow is the same.

Parsing and Building the DOM Tree ​

Parsing is one of the most important steps in the rendering engine. It is turning a document into a structure the browser can understand and use.

Lexical Analysis and Syntax Analysis ​

Parsing happens in two steps.

  1. Lexical analysis: cuts the document into tokens, the smallest meaningful units. In everyday language, it is like splitting a sentence into words. The part that does this is called the lexer (tokenizer).
  2. Syntax analysis: builds a parse tree while checking that the tokens are arranged according to the language's grammar rules. The part that does this is called the parser.
 <p>Hello <b>world</b></p>

 ① Lexical analysis →  [start:p] [text:Hello] [start:b] [text:world] [end:b] [end:p]
 ② Syntax analysis  →  p
                       ├── "Hello"
                       └── b
                           └── "world"

The parser asks the lexer for tokens one at a time, and if a token matches the grammar rules, it adds it to the parse tree as a node. If tokens that never match the rules are left at the end, the document is invalid and has a syntax error.

For a typical programming language, building the parse tree is followed by a step that translates it into machine code (compiles it). But a browser's HTML parsing does not produce machine code. The final result of HTML parsing is the DOM tree, and that DOM tree becomes the material for rendering.

Parser Generators and the HTML Parser ​

Writing a parser by hand is hard because grammar rules are complex and optimization is difficult, so people often use a parser generator that produces parser code from grammar rules. WebKit used to use Flex (a lexer generator) and Bison (a parser generator) for CSS parsing. Today both Chrome and Safari have switched to hand-written CSS parsers for speed.

However, HTML cannot be built with a parser generator. HTML is a very forgiving language and must show a page even when the grammar is wrong. So browsers use a dedicated parser that directly implements the tokenization algorithm and tree construction algorithm defined in the HTML specification.

  • Even if we forget the head tag by mistake, the parser creates a head element on its own.
  • Even if we leave out a closing </p> tag, the parser closes the previous paragraph when the next <p> appears.

Through parsing like this, the chunk of text received from the server becomes a DOM tree that the browser understands and can easily use.

A Closer Look at the Rendering Pipeline ​

Modern browsers split the basic flow above into finer steps. This sequence is also called the Critical Rendering Path.

StepWhat it doesAnalogy
1. Build the DOMParses HTML to build the DOM tree.Read the blueprint and list the rooms
2. Build the CSSOMParses CSS to build the style rule tree.Organize the interior design sheet
3. Build the render treeCombines the DOM and CSSOM. Elements that are not visible, such as those with display: none or head, are left out.Finalize the list of rooms that will actually be built
4. LayoutCalculates the position and size of each element. Box sizes follow the Box Model rules.Measure room sizes and positions with a tape measure
5. PaintPaints text, colors, shadows, images, and so on into pixels layer by layer.Paint the walls
6. CompositeStacks the separately painted layers in order to make the final screen. Mostly handled by the GPU.Stack several transparent films to finish

The difference between display: none and visibility: hidden: display: none is removed from the render tree entirely, so it takes up no space. visibility: hidden stays in the render tree, so it is just not visible and still takes up its space.

Reflow and Repaint ​

Even after the screen is drawn once, if styles change because of JavaScript or user actions, the browser runs part of the pipeline again.

TypeWhen it happensSteps redoneCost
ReflowWhen size or position changes (width, height, margin, font-size, window resize, adding/removing elements)Layout → Paint → CompositeHighest
RepaintWhen only the appearance changes (color, background-color, visibility)Paint → CompositeMedium
Composite onlyChanges to transform, opacity (when on a separate layer)CompositeLowest

A reflow is expensive because even when one element changes, the positions of its parent, children, and siblings may need to be recalculated. Chrome calls layout "Layout" and Firefox calls it "Reflow", but they mean the same thing.

How to Reduce Reflow ​

  • Animate with transform and opacity: moving with left and top causes a reflow every frame, but transform: translateX() redoes only the composite step. See also this site's Animation Effects article.
  • Change styles all at once: adding and removing one class is better than changing style.width and style.height one at a time.
  • Don't mix reads and writes: code that reads sizes, such as offsetWidth or getBoundingClientRect(), forces the browser to calculate any pending layout immediately so it can return up-to-date values. If you alternate writes and reads, a reflow happens every time. This is called forced synchronous layout (layout thrashing).
  • Add many elements in one batch: collect them in a DocumentFragment and attach them to the DOM at once.
  • Reduce the affected area: if you take frequently moving elements out of the document flow with position: absolute or fixed, they affect the position calculation of other elements less.

The Problem of script Tags Blocking Parsing ​

The HTML parser reads from top to bottom and stops parsing when it meets a <script> tag. JavaScript can change the document structure itself with document.write() or DOM manipulation, so the parser has to wait until the script is downloaded and run. This is called parser blocking.

That is why the standard practice used to be putting <script> right before </body>, and today we use the defer and async attributes.

Plain <script>
  HTML parsing   ████████▒▒▒▒▒▒▒▒▒▒████████
  JS download            ▓▓▓▓▓▓
  JS execution                 ░░░░  (parsing stops during download and execution)

<script async>
  HTML parsing   ██████████████▒▒▒▒████████
  JS download        ▓▓▓▓▓▓▓▓▓▓
  JS execution                 ░░░░  (runs as soon as the download finishes; parsing stops only then)

<script defer>
  HTML parsing   ██████████████████████████
  JS download        ▓▓▓▓▓▓▓▓▓▓
  JS execution                             ░░░░  (runs after parsing is completely done)
MethodDownloadWhen it runsExecution orderGood for
Plain <script>Stops parsing to downloadRight after downloadThe order writtenAlmost never (only when placed at the end of body)
asyncIn parallel with parsingRight after download (possibly during parsing)Not guaranteedIndependent scripts unrelated to other code, such as ads and visitor analytics
deferIn parallel with parsingAfter HTML parsing finishes, just before DOMContentLoadedThe order writtenMost scripts that work with the DOM

CSS has a similar problem. CSS does not block HTML parsing, but the render tree cannot be built until the CSSOM is complete, so it blocks rendering (Render Blocking). That is why it is best to put CSS in the head so it is fetched as early as possible.

Getting a Feel with Code: Turning Tags into a Tree ​

Let's read HTML line by line with Python's built-in html.parser and print the shape of the DOM tree ourselves. When we meet an opening tag, we indent one step, and when we meet a closing tag, we come back out one step.

python
from html.parser import HTMLParser

html = """
<html>
  <body>
    <h1>Hello</h1>
    <p>The browser turns <b>tags</b> into a tree</p>
  </body>
</html>
"""

class TreeBuilder(HTMLParser):
    def __init__(self):
        super().__init__()
        self.depth = 0          # how many levels deep we are right now

    def handle_starttag(self, tag, attrs):
        print("  " * self.depth + tag)     # opening tag = new node
        self.depth += 1                     # children go one level deeper

    def handle_endtag(self, tag):
        self.depth -= 1                     # closing tag = go back to the parent

    def handle_data(self, data):
        if data.strip():                    # skip lines that are only whitespace
            print("  " * self.depth + f'"{data.strip()}"')

TreeBuilder().feed(html)

Output:

html
  body
    h1
      "Hello"
    p
      "The browser turns"
      b
        "tags"
      "into a tree"

Next, let's imitate why reflow is expensive and what happens when you mix reads and writes. This is a simple model of the real browser rule: "when a style changes, just mark it, and when a size is read, calculate the pending layout".

python
# Compare how many times layout is recalculated (a model that imitates browser behavior)
class FakeBrowser:
    def __init__(self):
        self.dirty = False      # whether the layout is stale because a style changed
        self.layout_count = 0   # how many times layout (reflow) ran
        self.width = 100

    def set_width(self, value):         # style write: just mark it
        self.width = value
        self.dirty = True

    def read_offset_width(self):        # size read: if stale, lay out immediately
        if self.dirty:
            self.layout_count += 1
            self.dirty = False
        return self.width

# 1) Alternating writes and reads
b1 = FakeBrowser()
for i in range(100):
    b1.set_width(i)
    b1.read_offset_width()
print("Alternating reads and writes:", b1.layout_count, "reflows")

# 2) Doing the reads first, then batching the writes
b2 = FakeBrowser()
w = b2.read_offset_width()
for i in range(100):
    b2.set_width(w + i)
b2.read_offset_width()   # only once, right before the next frame is drawn
print("Reads first, batched writes:", b2.layout_count, "reflows")

Output:

Alternating reads and writes: 100 reflows
Reads first, batched writes: 1 reflows

Doing the same work in a different order cuts layout calculations from 100 to 1.

Interview Questions ​

Q. What happens when you type a URL into the address bar? The browser parses the URL, finds the domain's IP address through DNS, sets up a TCP connection with the server (plus TLS for https), and sends an HTTP request. When the server responds with HTML, the rendering engine parses the HTML and CSS to build the DOM and CSSOM, combines them into a render tree, and draws the screen through layout and paint.

Q. What is the DOM? It is a model that turns an HTML document into objects and represents them as a tree so that the browser and JavaScript can work with it. Through the DOM, JavaScript finds elements and changes their content and styles.

Q. What is the difference between reflow and repaint? A reflow recalculates layout because an element's size or position changed, and a repaint redraws because only the appearance, such as color, changed. A reflow is followed by a repaint, so a reflow is more expensive. For animations, it is best to use transform and opacity to avoid both.

Q. How do the async and defer attributes of the script tag differ? Both download the script in parallel with HTML parsing. async runs the script as soon as the download finishes and does not guarantee execution order. defer runs scripts in the order written after HTML parsing is completely done. Scripts that work with the DOM usually use defer.

Q. Why does a web page appear little by little instead of all at once? To show the user something quickly, the rendering engine does not wait until it has received all of the HTML. It parses the parts it has received and progressively runs layout and painting.

Summary ​

ConceptOne-line summary
Role of the browserRequests resources from the server and interprets the received resources according to standard specifications to display them on screen
7 basic componentsUser interface, browser engine, rendering engine, networking, UI backend, JS interpreter, data storage
Rendering enginesBlink for Chrome/Edge, WebKit for Safari, Gecko for Firefox
Big flowParse URL → DNS lookup → TCP/TLS connection → HTTP request/response → rendering
Rendering pipelineDOM → CSSOM → render tree → layout → paint → composite
DOMThe tree-structured object model through which the browser recognizes HTML
AttachmentIn WebKit, the process of connecting DOM nodes and style information to build the render tree
ParsingLexical analysis (cutting into tokens) + syntax analysis (building a tree while checking grammar). The result of HTML parsing is the DOM tree
Reflow / repaintSize and position changes redo from layout; color changes redo from paint
async / deferWays to avoid parser blocking. Use defer when order matters
Progressive renderingDraws the parts received so far before everything arrives, so the screen appears little by little