A Service Worker is a script the browser runs in a background thread, separate from the main page. It can intercept every network request the page makes via the fetch event, choose to serve from cache vs network vs both, and respond with whatever it wants -- enabling offline support, custom routing, and the "app shell" architecture that powers most PWAs.
Lifecycle (simplified):
- Register -- the page calls
navigator.serviceWorker.register('/sw.js'). The browser downloads the script and installs it (calling theinstallevent handler if any). - Activate -- once installed and any old service worker is gone, the new one activates and starts intercepting fetches.
- Fetch -- every network request from the controlling page fires a
fetchevent the worker can intercept.
Capabilities a service worker enables:
- Offline / poor-network UX: precache app-shell assets at install time, serve them from cache on subsequent visits.
- Push notifications: receive push messages from a server while the page is closed (subject to user permission).
- Background sync: defer state-changing requests until network returns.
- Custom caching strategies: stale-while-revalidate, cache-first-then-network, etc.
Constraints worth knowing:
- Service workers ONLY work on HTTPS (and
localhost). - They run in a separate global context with NO access to
window,document, or DOM. Communication with the page happens viapostMessage/ Broadcast Channel. - Worker upgrades are sticky: a new worker waits to activate until all controlled tabs close.
self.skipWaiting()andclients.claim()skip this, but read the docs first. - Debugging: Chrome DevTools > Application > Service Workers shows registered workers, their state, and lets you trigger updates / clear cache.
Worth flagging: navigator.serviceWorker.register(...) in the page bundle ONLY proves the registration is attempted. The worker may fail to install, fail to control any clients, or do nothing useful. BeaverCheck's PWA-depth check surfaces the registration call as a positive signal but doesn't (yet) probe the worker's behavior.