A service worker is a script that sits between your pages and the network for a scope, intercepting fetch events. Its lifecycle is register → install → (waiting) → activate → control pages. A new version installs in the background but waits until no tab is using the old one, so a page never has two versions of its worker mid-session. Pick a caching strategy per request type (cache-first for hashed assets, network-first or stale-while-revalidate for HTML and APIs), and treat updates as the hard part: a buggy worker can keep serving broken content until you ship a fix the worker itself lets through.
// sw.js
const VERSION = 'v42';
const PRECACHE = `precache-${VERSION}`;
self.addEventListener('install', (event) => {
event.waitUntil(caches.open(PRECACHE).then(c => c.addAll(['/offline.html', '/assets/app.3f9a.js'])));
});
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
const keys = await caches.keys();
await Promise.all(keys.filter(k => k !== PRECACHE).map(k => caches.delete(k)));
await self.clients.claim(); // take control of already-open pages
})());
});
clients.claim().sw.js on navigations (and at most roughly every 24 hours it bypasses the HTTP cache for that check). A byte difference in the script triggers a new install.self.skipWaiting() activates the new worker immediately, but already-open pages may then be running old JS against a new worker and new caches. Only do it if versions are compatible, or reload the clients.| Strategy | How | Use for |
|---|---|---|
| Cache first | Cache, fall back to network | Content-hashed static assets, fonts |
| Network first | Network, fall back to cache on failure or timeout | HTML, frequently changing API data |
| Stale-while-revalidate | Serve cache, update it in the background | Avatars, non-critical API data |
| Network only | Never cache | Analytics, payments, auth |
| Cache only | Precached | The app shell, offline page |
Workbox packages these with expiry, size limits and precache manifests generated by your build.
sw.js in the HTTP cache for long. Serve it with Cache-Control: no-cache.activate.waiting, then postMessage it to skipWaiting and reload on controllerchange.self.registration.unregister()). Also, the server can send Clear-Site-Data: "cache", "storage" in emergencies.no-cors) cross-origin responses: you can't check their status, so you may cache errors, and they count heavily against storage quota./js/sw.js can only control /js/ unless the server sends Service-Worker-Allowed.registration.navigationPreload for network-first HTML.navigator.storage.persist() for offline-critical apps.skipWaiting), cache versioning, and a kill switch, with a real incident if you have one.Spotted a mistake or a rights concern? Report an issue