Most service worker bugs are really lifecycle surprises. Learn these states and updates stop being mysterious.
The states
- Parsed and installing. The browser downloads the new
sw.js. Theinstallevent runs: this is where you precache files. - Installed, waiting. The new version is ready, but an older version is still controlling open tabs. It waits.
- Activating. When no tab uses the old version any more (all closed, or you told it to skip waiting), the new one activates. The
activateevent runs: delete old caches here. - Activated. It now handles
fetchfor every page in scope. - Redundant. Replaced, or installation failed.
Why the wait? Because two versions of your app running side by side, with different caches, would break things. The browser keeps the old one until it is safe.
How browsers find updates
- On every navigation to a page in scope, the browser fetches
sw.jsand compares it byte by byte. If anything changed, a new version installs. - At most once every 24 hours, the HTTP cache is bypassed for this check, and since 2018 browsers ignore the HTTP cache for
sw.jsitself by default (updateViaCache: 'imports'). Serve it withCache-Control: no-cacheanyway. - You can also call
registration.update(), for example when a tab becomes visible again.
Changing an imported script, or a precached file, does not trigger an update unless sw.js itself changes. That is why build tools put a hash or a version in it.
skipWaiting and clients.claim
self.addEventListener('install', () => self.skipWaiting()); // do not wait
self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim())); // take control now
skipWaiting()activates the new version straight away, even if tabs use the old one.clients.claim()makes the worker control open pages right away, including the very first page that registered it.
Calling skipWaiting() unconditionally is fine only if old pages can cope with new cache contents. If a page from version 1 lazily loads a script that version 2 deleted, it breaks. The safe pattern is to ask the user.
The "update available" pattern
In the service worker:
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') self.skipWaiting();
});
In the page:
const reg = await navigator.serviceWorker.register('/sw.js');
const offer = (worker) => showBanner('A new version is ready.', 'Reload', () => worker.postMessage({ type: 'SKIP_WAITING' }));
if (reg.waiting && navigator.serviceWorker.controller) offer(reg.waiting);
reg.addEventListener('updatefound', () => {
const w = reg.installing;
w.addEventListener('statechange', () => {
if (w.state === 'installed' && navigator.serviceWorker.controller) offer(w);
});
});
const hadController = !!navigator.serviceWorker.controller;
let reloading = false;
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (!hadController || reloading) return; // first install: no reload
reloading = true;
location.reload();
});
This is exactly what PWA.live does: when we publish a change, you see a small "new version" message with a Reload button.
Clearing old caches
Name caches with a version and delete the rest on activate:
const CURRENT = ['shell-v7', 'pages-v1', 'assets-v1'];
self.addEventListener('activate', (event) => {
event.waitUntil(caches.keys().then((keys) =>
Promise.all(keys.filter((k) => !CURRENT.includes(k)).map((k) => caches.delete(k)))));
});
Removing a service worker
To retire one, deploy a sw.js that unregisters itself:
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', async () => {
for (const k of await caches.keys()) await caches.delete(k);
await self.registration.unregister();
for (const c of await self.clients.matchAll({ type: 'window' })) c.navigate(c.url);
});
The Clear-Site-Data: "storage" response header also works, but it clears cookies and storage too.