The train goes into a tunnel and your phone loses signal. An ordinary site drops straight to the offline error page. A site with a service worker stays open, with the last data it managed to save.
A service worker is a JavaScript file the browser runs in the background, separate from the page, sitting between the page and the network. Every request from the page passes through it first, and it decides: answer from the cache, fetch from the network, or both. Picture a helper at home you send shopping. You ask for sugar, and the helper follows the rule you gave: check the kitchen cupboard first, or go straight to the shop, or hand you what's in the cupboard now while buying a fresh pack for next time.
Terms first
- Service worker: a JS file (usually
sw.js) with no access to the DOM. All it does is listen to events, mainly thefetchevent, which fires whenever the page asks for a file or data. - Cache Storage: a place in the browser for request and response pairs, reached through the
cachesobject. Unlike the normal HTTP cache, your code decides what goes in it. - Caching strategy: the rule "check the cache first or the network first" for each kind of request.
- A service worker only runs on HTTPS, except on
localhostfor development. The reason: it can replace every response, so it has to come from a trusted source.
The lifecycle: register, install, activate, fetch
The page registers the service worker with register. After that the service worker goes through three events, always in order install → activate → fetch:
- install: the new service worker is set up. This is usually where key files are saved to the cache ahead of time (precache).
- activate: the service worker takes charge. This is where old cache versions are deleted.
- fetch: once active, every request from the page goes through this event.
If an older service worker is already active, the new version finishes installing and then waits until every tab still controlled by the old version is closed. self.skipWaiting() in install makes it activate right away, and clients.claim() in activate makes it take over tabs that are already open.
Three strategies, tried in the Lab
The Lab on this page sends requests through a service worker. The times are a sensible simulation: about 5 ms from the cache, about 300 ms from the network. Here are three requests in a row per strategy, starting with an empty cache:
| Strategy | Request 1 (online) | Request 2 (online) | Request 3 (offline) |
|---|---|---|---|
| Cache first | network, 300 ms, then saved | cache, 5 ms | cache, 5 ms |
| Network first | network, 300 ms, then saved | network, 300 ms, latest data | cache, 5 ms, as a fallback |
| Stale-while-revalidate | network, 300 ms, then saved | cache, 5 ms, then the cache is refreshed in the background | cache, 5 ms |
- Cache first: for static assets that rarely change: CSS, JS, fonts, images. The fastest, but it can go stale.
- Network first: for data that must be current: API data, HTML pages, a balance. The cache is only a fallback when offline.
- Stale-while-revalidate: for things that may be a little stale: avatars, profiles, a category list. As fast as cache first, and the next visit gets the new version.
The code: sw.js with cache first
// sw.js
const CACHE = 'static-v1';
self.addEventListener('install', (event) => {
// precache: save key files before they are needed
event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(['/', '/css/main.css', '/js/app.js'])));
});
self.addEventListener('activate', (event) => {
// delete every cache whose name is not the current version
event.waitUntil(
caches.keys().then((keys) => Promise.all(keys.filter((key) => key !== CACHE).map((key) => caches.delete(key))))
);
});
self.addEventListener('fetch', (event) => {
const { request } = event;
// POST and requests to other domains: not intercepted, they go to the network as usual
if (request.method !== 'GET' || new URL(request.url).origin !== self.location.origin) return;
if (request.mode === 'navigate') {
// HTML pages: network first, `/` from the cache only as the offline fallback
event.respondWith(fetch(request).catch(() => caches.match('/')));
} else if (['style', 'script', 'font', 'image'].includes(request.destination)) {
event.respondWith(cacheFirst(request)); // static assets: cache first
}
// everything else, such as API data, also goes to the network
});
async function cacheFirst(request) {
const cached = await caches.match(request);
if (cached) return cached; // HIT: no network at all
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(CACHE);
cache.put(request, response.clone()); // a response body can only be read once
}
return response;
}
On the page: if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js');
event.waitUntil(...)holds install or activate open until its Promise settles.event.respondWith(...)takes over the answer to the request. Without it, the request goes to the network as usual.caches.matchsearches every cache; it givesundefinedwhen nothing matches.response.clone(): one copy goes into the cache, the other goes to the page.response.okistruefor status 200 to 299.cache.putwould also store a 404 or a 500, and it rejects a POST request with an error. So cache first here is only for successful GET requests for static assets.
The exercise version: the cache is a Map
In the exercise the cache is a Map (key url, value data), and the network is pretend: it always returns "fetched:" + url. Each method returns { source, data }, with the keys in exactly this order, source then data:
cacheFirst(url, cache) {
if (cache.has(url)) return { source: 'cache', data: cache.get(url) };
const fresh = 'fetched:' + url;
cache.set(url, fresh);
return { source: 'network', data: fresh };
}
cacheFirst('/css/main.css', cache) twice with the same Map: first { source: 'network', data: 'fetched:/css/main.css' }, then { source: 'cache', data: 'fetched:/css/main.css' }. If the Map already holds other data, say 'cached-font', cache first returns that as it is. Network first in this exercise is always online, so it always gives source: 'network' and still saves to the cache. Stale-while-revalidate returns the old cached value first, then fills the cache with 'fetched:' + url.
Cache versions and updates
Say you deploy new CSS under the same file name, /css/main.css. A returning visitor still gets the old CSS. Cache first finds /css/main.css in the cache, so the network is never asked, and the same URL means the same cached file, forever.
There are two ways out, usually used together:
- Hashed file names:
main.3f9a1c.css. The content changes, the hash changes, the URL is new, so it has to go to the network. - A versioned cache name: change
static-v1tostatic-v2insw.js. The browser checkssw.jswhenever a page opens; one changed byte makes it a new service worker. The new version installs, waits, then deletes thestatic-v1cache in activate.
Workbox: you don't have to write it all yourself
In real projects these strategies are usually written with Workbox, a library from Google (also used by vite-plugin-pwa):
import { registerRoute } from 'workbox-routing';
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies';
registerRoute(({ request }) => request.destination === 'style', new CacheFirst());
registerRoute(({ url }) => url.pathname.startsWith('/api/'), new NetworkFirst({ networkTimeoutSeconds: 3 }));
registerRoute(({ request }) => request.destination === 'image', new StaleWhileRevalidate());
⚠️ A cache that's stale, slow or broken
- Cache first for API data or HTML. Users keep seeing old data, because the network is never asked. Use network first or stale-while-revalidate.
- Never changing the cache version. Old caches pile up and old files keep being served. Rename the cache and delete the old one in
activate. - Forgetting
response.clone(). The response body was already read when it was saved, so the page gets a "body already used" error. - Network first with no time limit. On a slow network (not a dead one), users wait a long time before the cached fallback is used. Workbox has
networkTimeoutSeconds. - In the exercise: the key order must be
sourcethendata, and data from the cache comes back as it is; don't rebuild it as'fetched:' + url.
TL;DR: A service worker is background JS that intercepts every request through the fetch event. Its life: the page calls register, then install (precache), activate (delete old caches), fetch (intercept). A new version waits until old tabs close, unless you use skipWaiting and clients.claim. Cache first for static assets (fast, can go stale), network first for data that must be current (the cache is the offline fallback), stale-while-revalidate for things that may be a little stale. Use hashed file names and a versioned cache name so updates reach users. HTTPS is required, except on localhost. In real projects, use Workbox.
⚡ A gatekeeper between the page and the network
Meaning: A service worker is a JS file that runs in the background, separate from the page. Every request from the page passes through it first, through the fetch event, and it decides: answer from the cache, fetch from the network, or both. HTTPS is required, except on localhost.
⚡ Its lifecycle
Guess first: in what order do a service worker's events always run?
install → activate → fetch. Install saves key files to the cache (precache), activate deletes old cache versions, then fetch intercepts every request.
Meaning: A new version waits until every tab of the old version is closed, unless you use skipWaiting and clients.claim.
⚡ Three strategies
Write:
const cached = await caches.match(request);
if (cached) return cached; // HIT: no network at all
Meaning: Cache first for static assets that rarely change. Network first for data that must be current, with the cache as the offline fallback. Stale-while-revalidate for things that may be a little stale. Change the cache name's version (static-v1 to static-v2) so updates reach users.