avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

Browser Principles

  2023-06-13        
字数统计: 2.1k字   |   阅读时长: 12min

Browser Principles

Understanding how browsers work internally is essential for frontend developers to write efficient code and diagnose performance issues. This guide covers the key principles of modern web browsers.

Browser Architecture

Multi-Process Architecture

Modern browsers like Chrome use a multi-process architecture for better security, stability, and performance:

  • Browser Process: Controls the UI, handles user inputs, manages tabs, and coordinates with other processes
  • Renderer Process: Responsible for rendering web pages (one per tab or iframe in most cases)
  • Plugin Process: Runs plugins like Flash (increasingly rare)
  • GPU Process: Handles GPU tasks for rendering
  • Utility Processes: Handle various tasks like network requests, audio, etc.

Benefits of multi-process architecture:

  • If one tab crashes, other tabs remain unaffected
  • Security through process isolation (site isolation)
  • Better performance through parallelization

Threads in the Renderer Process

The renderer process contains several important threads:

  • Main Thread: Handles most tasks like HTML parsing, DOM tree construction, style calculations, layout, painting, and JavaScript execution
  • Compositor Thread: Creates composite layers and sends them to the GPU
  • Raster Threads: Perform rasterization of layers
  • Worker Threads: Run Web Workers, Service Workers, etc.

Rendering Pipeline

When a browser displays a webpage, it follows this rendering pipeline:

1. Navigation

  • User enters a URL
  • Browser process initiates a DNS lookup
  • Establishes TCP connection
  • Performs TLS handshake (for HTTPS)
  • Sends HTTP request
  • Receives response headers and body

2. DOM Construction

  • HTML Parsing: Converts HTML markup into a parse tree
  • DOM Tree Building: Creates the Document Object Model (DOM) tree
  • JavaScript Processing: If the parser encounters a script tag, it stops parsing, downloads (if needed), and executes the script before continuing
  • CSSOM Construction: Builds the CSS Object Model from stylesheets
1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h1>Hello World</h1>
<p>This is some text.</p>
</div>
<script src="script.js"></script>
</body>
</html>

For the above HTML, the DOM tree would roughly look like:

1
2
3
4
5
6
7
8
html
├── head
│ └── link
└── body
├── div
│ ├── h1 (Hello World)
│ └── p (This is some text.)
└── script

3. Render Tree Construction

  • Combines DOM and CSSOM
  • Only includes visible elements (excludes <head>, hidden elements, etc.)
  • Applies styles to each visible node

4. Layout (Reflow)

  • Calculates the exact position and size of each element in the viewport
  • Determines the location of lines, positions, widths, heights, etc.
  • Outputs a “box model” with precise coordinates

5. Paint

  • Creates layers if needed
  • Fills in pixels for each visual part of the elements (text, colors, borders, etc.)
  • Usually happens on multiple layers

6. Compositing

  • Combines the painted layers into the final image displayed on screen
  • Handles elements with different compositing properties (e.g., opacity, transform)

Critical Rendering Path Optimization

The Critical Rendering Path (CRP) is the sequence of steps the browser goes through to convert HTML, CSS, and JavaScript into actual pixels on the screen.

Optimizing the CRP

  1. Minimize bytes: Reduce file sizes through compression
  2. Reduce critical resources: Load only what’s needed for initial render
  3. Shorten the path length: Optimize the order of loading resources
1
2
3
4
5
6
<!-- Optimizing CSS delivery -->
<link rel="stylesheet" href="critical.css">
<link rel="stylesheet" href="non-critical.css" media="print" onload="this.media='all'">

<!-- Optimizing JS delivery -->
<script src="app.js" defer></script>

Script Loading Strategies

Blocking vs. Non-Blocking Scripts

By default, scripts block HTML parsing while they download and execute:

1
2
<!-- Blocking script -->
<script src="app.js"></script>

Options to prevent blocking:

1
2
3
4
5
<!-- Deferred script - loads in parallel with HTML parsing and executes after parsing -->
<script src="app.js" defer></script>

<!-- Async script - loads in parallel with HTML parsing and executes as soon as available -->
<script src="analytics.js" async></script>

defer vs. async

  • defer:

    • Downloads in parallel with HTML parsing
    • Executes in order after HTML is parsed but before DOMContentLoaded
    • Preserves execution order of multiple scripts
    • Ideal for scripts that need the full DOM and/or depend on each other
  • async:

    • Downloads in parallel with HTML parsing
    • Executes as soon as it’s downloaded, potentially before HTML is fully parsed
    • Does not guarantee execution order
    • Best for independent scripts like analytics

Module Scripts

1
<script type="module" src="app.js"></script>

Module scripts:

  • Are deferred by default
  • Use strict mode by default
  • Can use import/export
  • Are executed only once even if included multiple times

DOM Events

Event Flow Phases

DOM events follow a three-phase propagation model:

  1. Capture Phase: Event travels from the window down to the target element
  2. Target Phase: Event reaches the target element
  3. Bubbling Phase: Event bubbles up from the target to the window
1
2
3
4
5
6
7
8
9
// The third parameter (true) indicates capture phase
document.addEventListener('click', function(event) {
console.log('Capture phase');
}, true);

// The third parameter (false or omitted) indicates bubbling phase
element.addEventListener('click', function(event) {
console.log('Bubbling phase');
}, false);

Event Delegation

Event delegation leverages event bubbling to handle events at a higher level:

1
2
3
4
5
6
7
// Instead of adding event listeners to all list items
document.querySelector('ul').addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
// Handle the click on the list item
console.log('Clicked on:', event.target.textContent);
}
});

Benefits of event delegation:

  • Fewer event listeners = better performance
  • Dynamically added elements are automatically handled
  • Less memory usage

Stopping Event Propagation

1
2
3
4
5
6
7
8
9
10
element.addEventListener('click', function(event) {
// Prevents further propagation in capturing and bubbling phases
event.stopPropagation();

// Prevents any other listeners on the same element from being called
event.stopImmediatePropagation();

// For form submissions, links, etc.
event.preventDefault();
});

Browser Storage

Cookies

1
2
3
4
5
// Setting a cookie
document.cookie = "name=value; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/; domain=example.com; secure; samesite=strict";

// Reading cookies
const cookies = document.cookie;

Limitations:

  • ~4KB storage limit
  • Sent with every HTTP request (increasing bandwidth)
  • Can be secured with HttpOnly, Secure flags
  • SameSite attribute helps prevent CSRF attacks

localStorage and sessionStorage

1
2
3
4
5
6
7
8
9
// localStorage (persists across browser sessions)
localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
localStorage.removeItem('key');
localStorage.clear();

// sessionStorage (cleared when page session ends)
sessionStorage.setItem('key', 'value');
const tempValue = sessionStorage.getItem('key');

Limitations:

  • ~5MB storage limit (varies by browser)
  • Synchronous API (can block the main thread)
  • Limited to same-origin
  • Only stores strings (objects need JSON serialization)

IndexedDB

More powerful, asynchronous storage solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const request = indexedDB.open('myDatabase', 1);

request.onupgradeneeded = function(event) {
const db = event.target.result;
const objectStore = db.createObjectStore('customers', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
};

request.onsuccess = function(event) {
const db = event.target.result;
const transaction = db.transaction(['customers'], 'readwrite');
const objectStore = transaction.objectStore('customers');

objectStore.add({ id: 1, name: 'John', email: 'john@example.com' });

const getRequest = objectStore.get(1);
getRequest.onsuccess = function(event) {
console.log(event.target.result);
};
};

Benefits of IndexedDB:

  • Stores significant amounts of structured data
  • Supports transactions for data integrity
  • Asynchronous API doesn’t block the main thread
  • Can store almost any type of data

Cache API

Used with Service Workers for offline capabilities:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// In a service worker
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll([
'/',
'/styles.css',
'/app.js',
'/image.jpg'
]);
})
);
});

self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});

Browser Caching

HTTP Caching

Cache-Control Header

1
Cache-Control: max-age=3600, must-revalidate

Common directives:

  • max-age: Seconds the resource is fresh
  • no-cache: Must validate with server before using cached version
  • no-store: Don’t cache at all
  • public: Any cache can store the response
  • private: Only browser can cache, not intermediaries
  • must-revalidate: Must check if stale before using

ETag and If-None-Match

1
2
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"

The server can respond with 304 Not Modified if the resource hasn’t changed.

Last-Modified and If-Modified-Since

1
2
Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT
If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT

Types of Caching

  1. Browser Cache: Stores resources on the user’s device
  2. Proxy Caches: Intermediate caches between browser and origin server
  3. CDN Caches: Distributed caches that serve content from locations closer to the user

Strong vs. Weak Caching

Strong Caching (with Cache-Control): Browser uses cached version without checking with server until expiration.

Weak Caching (Conditional Requests): Browser verifies if cached resource is still valid using ETags or Last-Modified.

Browser Security Model

Same-Origin Policy

Prevents a script from one origin from accessing data from another origin. Origins consist of:

  • Protocol (http, https)
  • Domain (example.com)
  • Port (80, 443)
1
2
// This will fail if the origins don't match
fetch('https://another-domain.com/data').then(response => response.json());

Cross-Origin Resource Sharing (CORS)

Relaxes the same-origin policy using HTTP headers:

1
2
3
4
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true

For complex requests, browsers send a preflight OPTIONS request first.

Content Security Policy (CSP)

Restricts resource loading and execution:

1
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.com; img-src *

Can be set via HTTP header or meta tag:

1
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

Performance Considerations

Reflow and Repaint

Reflow (or Layout) is recalculating element positions and dimensions. It’s triggered by:

  • DOM manipulation (adding/removing nodes)
  • Changing element dimensions or position
  • Changing font, text content, or images that affect dimensions
  • Querying certain element properties (offsetHeight, getComputedStyle, etc.)

Repaint happens when visual styles change without affecting layout:

  • Color changes
  • Visibility changes
  • Background image changes

Reflows are more expensive than repaints. Minimize them by:

1
2
3
4
5
6
7
8
9
// Bad: Causes multiple reflows
element.style.width = '100px';
element.style.height = '100px';
element.style.margin = '10px';

// Better: Batch style changes
element.style.cssText = 'width: 100px; height: 100px; margin: 10px;';
// Or use class changes
element.className = 'my-styled-element';

Rendering Performance Tips

  1. Reduce layout thrashing: Batch DOM reads and writes
  2. Use will-change for animations: Hints the browser about upcoming changes
  3. Use transform and opacity for animations: These can be offloaded to the compositor thread
  4. Avoid forced synchronous layouts: Don’t mix reads and writes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Bad: Causes layout thrashing
for (let i = 0; i < elements.length; i++) {
const height = elements[i].offsetHeight; // Read (forces layout)
elements[i].style.height = (height * 2) + 'px'; // Write (invalidates layout)
}

// Better: Separate reads and writes
const heights = [];
for (let i = 0; i < elements.length; i++) {
heights.push(elements[i].offsetHeight); // Read
}
for (let i = 0; i < elements.length; i++) {
elements[i].style.height = (heights[i] * 2) + 'px'; // Write
}

requestAnimationFrame

Use for smooth visual updates:

1
2
3
4
5
6
7
8
9
10
11
function animate() {
// Update DOM here
element.style.transform = `translateX(${position}px)`;
position += 5;

if (position < 1000) {
requestAnimationFrame(animate);
}
}

requestAnimationFrame(animate);

Benefits:

  • Syncs with the browser’s rendering cycle
  • Pauses in inactive tabs
  • More efficient than setInterval/setTimeout for animations

Browser DevTools

Modern browsers provide powerful developer tools for debugging rendering issues:

  • Performance Panel: Records and analyzes runtime performance
  • Rendering Tool: Visualizes repaints, layout shifts, and layer borders
  • Memory Panel: Investigates memory issues and leaks
  • Network Panel: Analyzes resource loading and caching
  • Application Panel: Inspects storage, service workers, and manifest

Learning Resources

  • Chrome Developers - Inside Browser
  • MDN Web Docs - Browser Rendering
  • web.dev - Rendering Performance
  • HTML5Rocks - Reflows & Repaints
  • MDN Web Docs - HTTP Caching
  • Chrome DevTools Documentation

Understanding browser principles helps you write more efficient code, debug complex issues, and optimize user experience. These concepts are particularly important for frontend interviews at top companies.

  • Web Development
  • Browser
  • Rendering
  • Performance

扫一扫,分享到微信

微信分享二维码
Web Security
Frontend Interview Preparation Guide
目录
  1. 1. Browser Principles
    1. 1.1. Browser Architecture
      1. 1.1.1. Multi-Process Architecture
      2. 1.1.2. Threads in the Renderer Process
    2. 1.2. Rendering Pipeline
      1. 1.2.1. 1. Navigation
      2. 1.2.2. 2. DOM Construction
      3. 1.2.3. 3. Render Tree Construction
      4. 1.2.4. 4. Layout (Reflow)
      5. 1.2.5. 5. Paint
      6. 1.2.6. 6. Compositing
    3. 1.3. Critical Rendering Path Optimization
      1. 1.3.1. Optimizing the CRP
    4. 1.4. Script Loading Strategies
      1. 1.4.1. Blocking vs. Non-Blocking Scripts
      2. 1.4.2. defer vs. async
      3. 1.4.3. Module Scripts
    5. 1.5. DOM Events
      1. 1.5.1. Event Flow Phases
      2. 1.5.2. Event Delegation
      3. 1.5.3. Stopping Event Propagation
    6. 1.6. Browser Storage
      1. 1.6.1. Cookies
      2. 1.6.2. localStorage and sessionStorage
      3. 1.6.3. IndexedDB
      4. 1.6.4. Cache API
    7. 1.7. Browser Caching
      1. 1.7.1. HTTP Caching
        1. 1.7.1.1. Cache-Control Header
        2. 1.7.1.2. ETag and If-None-Match
        3. 1.7.1.3. Last-Modified and If-Modified-Since
      2. 1.7.2. Types of Caching
      3. 1.7.3. Strong vs. Weak Caching
    8. 1.8. Browser Security Model
      1. 1.8.1. Same-Origin Policy
      2. 1.8.2. Cross-Origin Resource Sharing (CORS)
      3. 1.8.3. Content Security Policy (CSP)
    9. 1.9. Performance Considerations
      1. 1.9.1. Reflow and Repaint
      2. 1.9.2. Rendering Performance Tips
      3. 1.9.3. requestAnimationFrame
    10. 1.10. Browser DevTools
    11. 1.11. Learning Resources

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号