PWA Service Workers Deep Dive
Master the Service Worker lifecycle, events, caching, and update flow for Progressive Web Apps.
What you'll learn
- Service Worker lifecycle: install, activate, fetch
- Cache API for offline resource storage
- Update flow: skipWaiting and clients.claim
- Scope, registration, and versioning strategies
Concept
PWA Service Workers Deep Dive
A Service Worker is a JavaScript worker running in the background, acting as a programmable network proxy for PWAs.
Lifecycle
Registration: page calls navigator.serviceWorker.register(). Install: pre-cache critical assets. Activate: clean up old caches. Fetch: intercept all network requests within scope.
Cache API
The Cache API stores Response objects keyed by Request. Open a named cache, put responses, match requests. Multiple caches can coexist for versioning.
Update Flow
When you deploy a new SW, the browser detects byte difference and installs it. The new SW waits until all tabs with the old SW close. skipWaiting() forces immediate activation.
Scope and Versioning
SW scope is its directory by default. Version by changing file content (even a comment). Use version strings in cache names (v1, v2) to manage cache lifecycle.
Example
navigator.serviceWorker.register('/sw.js', {scope:'/'}).then(reg => console.log('SW registered:', reg.scope));
// sw.js:
const CACHE = 'app-v1'; const ASSETS = ['/', '/index.html', '/styles.css', '/app.js'];
self.addEventListener('install', e => e.waitUntil(caches.open(CACHE).then(c => c.addAll(ASSETS)).then(() => self.skipWaiting())));
self.addEventListener('activate', e => e.waitUntil(caches.keys().then(ks => Promise.all(ks.filter(k => k !== CACHE).map(k => caches.delete(k)))).then(() => self.clients.claim())));
self.addEventListener('fetch', e => e.respondWith(caches.match(e.request).then(c => c || fetch(e.request).then(r => { caches.open(CACHE).then(c => c.put(e.request, r.clone())); return r; }))));
console.log('SW code defined');
The SW pre-caches assets on install, deletes old caches on activate, and uses cache-first strategy on fetch. skipWaiting enables immediate updates.
Try it
- JSON Formatter
Cache API stores Response objects - inspect cached JSON during development.
Common mistakes
The mistake
Caching too aggressively, serving stale content forever.
The fix
For HTML, use network-first or stale-while-revalidate to ensure fresh content.
The mistake
Not handling cache storage limits.
The fix
Use navigator.storage.estimate() to check usage and evict old caches proactively.
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.