← Back to Frontend, page 2

frontend-0022 · Medium mid

What is a service worker, how does its lifecycle work, and how do you serve a file from the cache when the user is offline?

A service worker is a script that runs in the background and sits between the page and the network. It goes through install, waiting and activate, and once active it can answer fetch events from the Cache Storage, so a cached file works offline.

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:

  1. Register. The page calls navigator.serviceWorker.register('/sw.js'). The scope defaults to the folder of the script, so a script at /sw.js can control the whole site.
  2. Install. The install event fires once for a new script. This is the place to pre-cache files with event.waitUntil(...). The worker does not move on until the promise settles.
  3. Waiting. If an older worker still controls open pages, the new one waits until those pages are closed, unless it calls skipWaiting().
  4. Activate. The activate event is the place to delete old caches. The worker controls only pages that load after activation, unless it calls clients.claim(). This is why the first visit is not controlled, and a reload is.
  5. Fetch. Each request from a controlled page triggers a fetch event. The worker calls event.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.

javascript
// 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.