Service Worker Caching — Performance

A service worker is background JS that intercepts every request through the fetch event. Its life: the page calls register, then install (precache), activate…

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

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:

  1. install: the new service worker is set up. This is usually where key files are saved to the cache ahead of time (precache).
  2. activate: the service worker takes charge. This is where old cache versions are deleted.
  3. 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

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');

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:

  1. Hashed file names: main.3f9a1c.css. The content changes, the hash changes, the URL is new, so it has to go to the network.
  2. A versioned cache name: change static-v1 to static-v2 in sw.js. The browser checks sw.js whenever a page opens; one changed byte makes it a new service worker. The new version installs, waits, then deletes the static-v1 cache 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

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.

What you will learn