Full answer
A service worker is a JavaScript file registered by a page. It runs in its own thread, has no access to the DOM and works on the origin level. It needs a secure context: HTTPS, or localhost for development.
Lifecycle:
- Register. The page calls
navigator.serviceWorker.register('/sw.js'). Thescopedefaults to the folder of the script, so a script at/sw.jscan control the whole site. - Install. The
installevent fires once for a new script. This is the place to pre-cache files withevent.waitUntil(...). The worker does not move on until the promise settles. - Waiting. If an older worker still controls open pages, the new one waits until those pages are closed, unless it calls
skipWaiting(). - Activate. The
activateevent is the place to delete old caches. The worker controls only pages that load after activation, unless it callsclients.claim(). This is why the first visit is not controlled, and a reload is. - Fetch. Each request from a controlled page triggers a
fetchevent. The worker callsevent.respondWith(...)with a response from the cache, the network or a mix.
The snippet uses the simplest strategy, cache first. During install it stores / and /data.json. In fetch it answers from the cache if there is a match and falls back to the network. Offline, the stored files are still served.
Strategy choice is a design decision. Cache first suits files that never change at the same URL, such as hashed assets. Network first suits data that should be fresh and falls back to the cache offline. Stale-while-revalidate answers at once from the cache and updates it in the background.
Important limits: the cache has no automatic expiry, so you must manage versions. The Cache API stores only responses to GET requests. Storage is limited and the browser may remove it under pressure.
// page script: register the worker
if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js');
// ---- sw.js
const CACHE = 'static-v1';
self.addEventListener('install', (event) => {
event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(['/', '/data.json'])));
});
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
event.respondWith(caches.match(event.request).then((hit) => hit || fetch(event.request)));
});Run in headless Chrome 156 through Playwright. Two full runs gave the same results. A local server on localhost was used, which counts as a secure context. After a reload the page was controlled, and with the browser set offline the cached data file and the home page were still returned. Other browsers and real network loss were not tested.
Key points
- A service worker is a background script between the page and the network.
- Lifecycle: register, install, waiting, activate, then fetch events.
- Pre-cache in install. Delete old caches in activate.
- A new page load is needed for control, unless clients.claim is used.
- Choose cache first, network first or stale-while-revalidate per resource type.
Common mistakes
- Testing on plain HTTP over a real host name, where registration is not allowed.
- Expecting the worker to control the page on the first visit.
- Caching HTML cache first, so users never see a new version.
- Forgetting that the worker has no DOM access.
Follow-ups
- What does event.waitUntil do?
- How does a service worker differ from the HTTP cache?
- When would you choose network first?
Tips
- Walk through the lifecycle in order and say what each event is for.
- Say why the first visit is not controlled, because it shows real experience.