A programmable network proxy
A service worker is a script the browser runs in the background, separate from a page, acting as a proxy between the app and the network. It enables offline support, caching, and push notifications.
- It runs on its own thread with no DOM access
- It must be served over HTTPS for security
- It has a defined lifecycle you must respect
The lifecycle stages
- Register: the page calls register to point at the worker script
- Install: fires once per new worker, ideal for precaching assets
- Activate: fires after install, the place to clean up old caches
- Idle and fetch: the active worker intercepts network requests
The update trap
A new worker installs but stays waiting until all tabs controlled by the old worker close. Calling skipWaiting in install and clients claim in activate lets a new worker take control immediately.
Key idea
A service worker moves through install and activate; a new version waits until old clients close unless skipWaiting and clients claim let it take over right away.