PWA Caching Strategies Deep Dive
Implement cache-first, network-first, stale-while-revalidate, and cache-only strategies with the Cache API.
What you'll learn
- Cache-first: fast, may serve stale data
- Network-first: fresh, falls back to cache offline
- Stale-while-revalidate: fast AND fresh
- Cache-only and network-only edge cases
Concept
PWA Caching Strategies Deep Dive
The Service Worker fetch event is where you decide how to handle each request based on resource type.
Cache-First
Check cache first; if found, return it. If not, fetch from network, cache, and return. Best for static assets (images, fonts). Drawback: may serve stale content.
Network-First
Try network first; if it succeeds, cache and return. If offline, return cached version. Best for fresh content (API responses, articles). Drawback: slower.
Stale-While-Revalidate
Return cached immediately AND fetch from network to update cache. Next request gets fresh version. Best general-purpose strategy - fast and fresh.
Routing Strategies
Route different URL patterns to different strategies: HTML -> network-first, JS/CSS -> stale-while-revalidate, images -> cache-first. This optimizes for each resource type.
Example
const C = 'strat-v1';
async function cacheFirst(r) { const c = await caches.match(r); if (c) return c; const f = await fetch(r); (await caches.open(C)).put(r, f.clone()); return f; }
async function networkFirst(r) { try { const f = await fetch(r); (await caches.open(C)).put(r, f.clone()); return f; } catch { return caches.match(r); } }
async function swr(r) { const c = await caches.open(C); const cached = await c.match(r); const fp = fetch(r).then(f => { c.put(r, f.clone()); return f; }).catch(() => cached); return cached || fp; }
self.addEventListener('fetch', e => { const u = new URL(e.request.url); if (u.pathname.endsWith('.html')) e.respondWith(networkFirst(e.request)); else if (u.pathname.match(/\.(css|js)$/)) e.respondWith(swr(e.request)); else e.respondWith(cacheFirst(e.request)); });
console.log('Strategies defined');
Three strategies implemented. Router applies network-first to HTML, SWR to CSS/JS, cache-first to images. SWR returns cached while updating in background.
Try it
- JSON Diff
Compare cached vs fresh responses - SWR shows the difference.
Common mistakes
The mistake
Using cache-first for HTML documents.
The fix
HTML changes when you deploy. Use network-first or SWR for HTML to ensure fresh content.
The mistake
Not cloning responses before caching.
The fix
A Response can only be consumed once. Always clone: cache.put(request, response.clone()).
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.