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

EventUse
installPrecache required shell assets
activateClean old caches and migrate assumptions
fetchServe cached/fresh responses and offline fallback
pushReceive push messages and display notifications
syncRetry deferred work where supported
notificationclickFocus 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() and clients.claim().