Service Workers
A service worker is an event-driven worker that can intercept network requests for pages it controls. It has no DOM access and can be stopped between events.
Registration
if ('serviceWorker' in navigator) {
window.addEventListener('load', async () => {
const registration = await navigator.serviceWorker.register('/sw.js', {
scope: '/',
});
console.log('Service worker registered', registration.scope);
});
}
Lifecycle
stateDiagram-v2
[*] --> Installing
Installing --> Installed: install event succeeds
Installed --> Waiting: old clients still open
Waiting --> Activating: clients close or skipWaiting
Activating --> Activated: activate event succeeds
Activated --> Redundant: replaced or failed
Events You Actually Design For
| Event | Use |
|---|---|
install | Precache required shell assets |
activate | Clean old caches and migrate assumptions |
fetch | Serve cached/fresh responses and offline fallback |
push | Receive push messages and display notifications |
sync | Retry deferred work where supported |
notificationclick | Focus or open the right app route |
Rules
- Register the service worker from a stable URL near the app root.
- Keep first load usable even before the worker controls the page.
- Persist state in IndexedDB or server data, not worker globals.
- Version caches and delete old caches during activation.
- Plan update UX before forcing
skipWaiting()andclients.claim().