Service Worker Lifecycle And Updates
Service worker updates are where many PWAs break after the first successful demo.
Update Model
- Browser checks the service worker script for byte changes.
- New worker installs.
- If existing controlled clients are open, the new worker waits.
- It activates after old clients close, or earlier if you call
skipWaiting(). - Activated worker controls future pages, or existing pages after
clients.claim().
Safe Update UX
if ('serviceWorker' in navigator) {
const registration = await navigator.serviceWorker.ready;
registration.addEventListener('updatefound', () => {
const worker = registration.installing;
worker?.addEventListener('statechange', () => {
if (worker.state === 'installed' && navigator.serviceWorker.controller) {
showUpdateAvailableToast();
}
});
});
}
Cache Migration Rules
- Cache names include a version.
- Activation deletes old cache versions.
- HTML is not cached forever.
- JS and CSS are fingerprinted by the build.
- Update prompt reloads all app tabs or clearly warns the user.
- Outbox and user data migrations are separate from asset cache cleanup.
Gotcha:
skipWaiting()plusclients.claim()can be correct for simple apps, but it can also put old pages under a new worker. Use it only with an update strategy you have tested.