Data URIs vs External Files: Complete Comparison
Compare data URIs against external file references for images, fonts, and other assets. Analyze HTTP/2 impact, caching, CDN benefits, and real-world scenarios.
Detailed Explanation
Data URIs vs External Files
Choosing between inline data URIs and external file references is a nuanced decision that depends on file size, usage frequency, caching strategy, and network protocol.
Feature Comparison
| Feature | Data URI | External File |
|---|---|---|
| HTTP requests | None | 1 per file |
| Browser caching | With parent document | Independent |
| File size | +33% (Base64) | Original size |
| CDN support | Through parent doc | Direct CDN caching |
| HTTP/2 push | N/A | Server push capable |
| Shared across pages | Duplicated in each page | Cached once, used everywhere |
| Update strategy | Re-deploy parent | Cache-bust individual file |
| Lazy loading | Not applicable | Supports loading="lazy" |
When Data URIs Win
- Small files (<4 KB) — HTTP overhead exceeds Base64 overhead
- Critical render path — Images needed before First Contentful Paint
- Single-use images — Used on only one page
- Offline requirements — Service workers cache the entire document
- Email templates — External images often blocked
- CSS icon systems — SVG icons self-contained in stylesheet
When External Files Win
- Large files (>10 KB) — Specialized compression is more efficient
- Shared resources — Same image on multiple pages benefits from caching
- Frequently changing assets — Independent cache invalidation
- HTTP/2 environments — Request multiplexing reduces overhead
- Lazy-loaded content — Below-the-fold images should not increase initial payload
- Responsive images —
srcsetneeds multiple external sources
HTTP/2 Changes the Calculus
HTTP/2 multiplexing allows hundreds of concurrent requests over a single connection. This reduces the per-request overhead significantly, making external files more competitive for small assets. However, each request still has framing overhead (~9 bytes per frame) and head-of-line blocking can occur.
Hybrid Strategy
The optimal approach often combines both:
- Inline: Critical above-the-fold icons and logos as data URIs
- External: Large images, shared assets, and below-the-fold content
- Build tool automation: Let Webpack or Vite handle the threshold automatically
// Webpack url-loader example
{
test: /\.(png|jpg|gif|svg)$/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 4 * 1024 // 4 KB threshold
}
}
}
Use Case
You are configuring a Webpack build pipeline for a large e-commerce site and need to set the optimal threshold for automatic data URI inlining of image assets.