# Resource Loading and Critical Rendering Path The browser converts raw bytes into rendered pixels through a precise pipeline. Understanding this pipeline reveals exactly which resources block rendering and how to eliminate or defer them. ## Table of Contents 1. [The Critical Rendering Path](#the-critical-rendering-path) 2. [Render-Blocking Resources](#render-blocking-resources) 3. [Async and Defer](#async-and-defer) 4. [Resource Hints](#resource-hints) 5. [Font Loading Strategies](#font-loading-strategies) 6. [Image Optimization](#image-optimization) 7. [Resource Loading Priority](#resource-loading-priority) 8. [Practical Loading Strategy](#practical-loading-strategy) --- ## The Critical Rendering Path Every page load follows this sequence: ``` HTML bytes → Parse → DOM ↓ CSS bytes → Parse → CSSOM ↓ Render Tree (DOM + CSSOM) ↓ Layout (geometry calculation) ↓ Paint (pixel rendering) ↓ Composite (layer assembly) ``` **The key insight:** The browser cannot paint anything until both the DOM and CSSOM are complete. CSS is **render-blocking**. JavaScript is **parser-blocking**. Every blocking resource directly adds to time-to-first-paint. ### DOM Construction The browser receives HTML bytes, decodes them into characters, tokenizes them into tags, and builds the DOM tree. This is incremental -- the parser processes HTML as it arrives, building the tree progressively. **When parsing stops:** - A `
This paragraph waits
``` ## Async and Defer The `async` and `defer` attributes change how scripts interact with the parser: ### `defer` ```html ``` - Downloads in parallel with DOM parsing (non-blocking) - Executes **after** DOM parsing is complete, before `DOMContentLoaded` - Multiple deferred scripts execute in document order - **Best for:** Most application scripts that depend on the DOM ### `async` ```html ``` - Downloads in parallel with DOM parsing (non-blocking) - Executes **immediately** when download completes (may interrupt parsing) - No guaranteed execution order between multiple async scripts - **Best for:** Independent scripts that do not depend on DOM or other scripts (analytics, ads) ### Comparison | Attribute | Download | Execution | Order guaranteed | Blocks parsing | |-----------|----------|-----------|-----------------|----------------| | None | Sequential | Immediately | Yes | Yes | | `async` | Parallel | When ready | No | Briefly (during execution) | | `defer` | Parallel | After DOM parsed | Yes | No | ### Module scripts ```html ``` Module scripts are deferred by default. Adding `async` to a module script makes it execute as soon as its dependency graph is resolved. ## Resource Hints Resource hints allow developers to inform the browser about resources it will need, enabling earlier loading. ### `dns-prefetch` Resolves the DNS for a domain before any request is made: ```html ``` - Cheapest hint -- only does DNS resolution - Use for third-party domains (analytics, fonts, CDNs) - Saves 20-120ms per domain ### `preconnect` Resolves DNS, establishes TCP connection, and negotiates TLS: ```html ``` - More expensive than `dns-prefetch` (holds a connection open) - Use for origins you will definitely request from within seconds - Limit to 2-4 critical origins to avoid wasting connections - Always include `crossorigin` for CORS-enabled resources: ```html ``` ### `preload` Fetches a specific resource at high priority without blocking rendering: ```html ``` - **The `as` attribute is required** -- it sets the correct priority and CORS mode - Fetches immediately at high priority - Does not apply the resource (does not render CSS, execute JS, etc.) - Use for critical resources discovered late in the HTML (fonts referenced in CSS, images in CSS backgrounds) - **Warning:** Preloading too many resources dilutes the benefit -- limit to truly critical resources (LCP image, critical fonts) ### `prefetch` Fetches a resource at low priority for a likely future navigation: ```html ``` - Downloaded at lowest priority during idle time - Stored in the HTTP cache for future use - Use for resources needed on the next likely page (next step in a flow, frequently visited page) - Does not work if the user has Data Saver enabled ### `prerender` / Speculation Rules Modern browsers support the Speculation Rules API for prerendering entire pages: ```html ``` - Renders the entire page in a hidden tab - Near-instant navigation when the user clicks - Expensive in terms of memory and bandwidth -- use only for high-confidence predictions ## Font Loading Strategies Web fonts create unique performance challenges because the browser may hide text while fonts load (Flash of Invisible Text, or FOIT) or show a jarring swap (Flash of Unstyled Text, or FOUT). ### `font-display` values ```css @font-face { font-family: 'Custom Font'; src: url('font.woff2') format('woff2'); font-display: swap; /* Show fallback immediately, swap when ready */ } ``` | Value | Behavior | Best for | |-------|----------|----------| | `auto` | Browser default (usually FOIT for 3s) | Not recommended | | `block` | Invisible text for up to 3s, then swap | Icon fonts only | | `swap` | Show fallback immediately, swap when loaded | Body text, most use cases | | `fallback` | Brief invisible period (100ms), then fallback, then swap | Balanced approach | | `optional` | Brief invisible period, uses font only if cached | Performance-critical; accepts FOUT | ### Preloading fonts Fonts referenced in CSS are discovered late -- the browser must load HTML, then CSS, then discover the font URL. Preloading jumps the queue: ```html ``` The `crossorigin` attribute is required even for same-origin fonts because the font specification requires CORS. ### Font subsetting Subset fonts to include only the characters needed: - Latin-only sites can drop CJK, Cyrillic, and other ranges - Use `unicode-range` in `@font-face` to load character ranges on demand ```css @font-face { font-family: 'Custom Font'; src: url('font-latin.woff2') format('woff2'); unicode-range: U+0000-00FF; /* Basic Latin */ } ``` ## Image Optimization Images typically account for 50-70% of total page weight. ### Lazy loading ```html
```
### Responsive images
Serve appropriately sized images for each viewport:
```html
```
### Modern formats
| Format | Compression | Browser support | Best for |
|--------|-------------|-----------------|----------|
| **AVIF** | Best (50% smaller than JPEG) | Chrome, Firefox, Safari 16+ | Photos, complex images |
| **WebP** | Good (25-35% smaller than JPEG) | All modern browsers | General purpose |
| **JPEG** | Baseline | Universal | Fallback |
| **PNG** | Lossless | Universal | Transparency, screenshots |
| **SVG** | Vector (tiny for icons) | Universal | Icons, logos, illustrations |
Use the `
```
```css
img {
aspect-ratio: 4 / 3;
width: 100%;
height: auto;
}
```
## Resource Loading Priority
Modern browsers assign priorities based on resource type and position. The `fetchpriority` attribute gives developers explicit control:
```html
```
### Default browser priorities
| Resource | Default priority |
|----------|-----------------|
| HTML document | Highest |
| CSS in `` | Highest |
| Preloaded resources | High |
| Scripts in `` | High |
| Images in viewport | High |
| Scripts at end of body | Medium |
| Images out of viewport | Low |
| Prefetched resources | Lowest |
## Practical Loading Strategy
A complete resource loading strategy for a typical page:
```html
```
This ordering ensures critical resources load first, nothing blocks rendering unnecessarily, and resources for future navigations are prepared during idle time.