A programmable proxy
A service worker is a script that sits between your page and the network. Once registered and activated, it can intercept requests and decide whether to answer from the cache or the network. This is what makes installable web apps work offline.
Lifecycle
- Install runs once and is where you precache the app shell.
- Activate runs after install and is where you clean up old caches.
- Fetch runs for every network request the page makes.
A new service worker waits until existing pages close before taking control, which avoids breaking a running app mid session.
Caching strategies
- Cache first serves from cache and falls back to network. Great for static assets.
- Network first tries the network and falls back to cache. Good for fresh content.
- Stale while revalidate serves cache immediately and updates it in the background.
Service workers require HTTPS because intercepting traffic is powerful and must be secure.
Key idea
A service worker intercepts requests and chooses cache or network per strategy, enabling offline support, but only over HTTPS and with careful cache versioning.