Service Worker
A service worker is an event-driven browser worker that can control requests and provide offline or background behavior for pages in its scope.
Download Markdown (.md)Soroush’s Product Wiki · https://wiki.soroush.uk/topic/service-worker/
01What it means
A service worker is a script registered for an origin and path scope that runs separately from documents, has no direct DOM access, and can intercept controlled fetches. Its install and activation lifecycle supports programmable caching and, where available, background capabilities such as push and synchronization. It requires a secure context in normal deployment.[1][2]
- RegisterPage defines scope
- InstallPrepare version
- ActivateReplace safely
- ControlHandle events
- UpdateNew script starts lifecycle
A newer version repeats install and activation
Updates can wait beside an active version.
02Why it matters
Service workers enable resilient network strategies and background experiences, but they sit between an application and the network. A faulty or stale worker can break every controlled visit and persist beyond a normal page deployment.
03When to use it
Use a service worker when offline tasks, explicit caching strategies, push, or background work create demonstrated user value. Do not add one only to qualify a site as a PWA; ordinary HTTP caching is safer for many products.
04How it works
- A secure page registers a worker script with a defined scope.
- The browser downloads it and runs install before activating a successful version.
- After activation, the worker can control matching clients and receive lifecycle events.
- Fetch handlers choose network, cache, generated, or fallback responses.
- Update and cleanup logic replaces old versions and removes obsolete cached data.
05A practical example
A transit timetable caches the application shell and recently viewed routes, serves a clear offline fallback for uncached journeys, and updates cached schedules with versioned cleanup after a new worker activates.
06Where it breaks
Lifecycle and multi-tab updates are subtle, storage may be evicted, background execution is constrained, and platform support varies. Interception adds startup and debugging cost, and cached private data needs careful controls.
Common mistakes
- Caching every response indefinitely without versioning or privacy rules.
- Activating an incompatible worker while older tabs are still running.
- Assuming the worker is continuously alive in the background.
- Confusing Cache Storage with the browser's HTTP cache.
07Sources
- Service Worker APIMDN Web Docs · Official technical documentationService Worker API
- Service WorkersW3C · Web standardService Workers