Skip to content
jshacks.dev
Performance

Cache fetch responses in service worker

Serve repeat requests from the Cache API in a service worker with a cache-first fetch handler, and update the stored copy in the background.

1 min read
Summarize in AI

A service worker sits between the page and the network, so it can answer from a local cache and skip the request. This stale-while-revalidate handler returns the cached copy and refreshes it in the background.

sw.jsJavaScript
const CACHE = 'assets-v1';

self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') return;

  event.respondWith(
    caches.open(CACHE).then(async (cache) => {
      const cached = await cache.match(event.request);
      const network = fetch(event.request).then((response) => {
        if (response.ok) cache.put(event.request, response.clone());
        return response;
      });
      return cached ?? network;
    }),
  );
});
Text
first visit:  GET /app.css  -> network (stored in assets-v1)
second visit: GET /app.css  -> served from cache, refreshed in the background

response.clone() is required because a response body can be read once: one copy goes to the cache and the other to the page. cache.match finds a stored response for the same request.

Register the worker from the page with navigator.serviceWorker.register('/sw.js'). Cache only responses that are safe to reuse and never ones with personal data. Change the cache name when you ship new assets and delete old caches in the activate event, or users may keep stale files. See Using Service Workers.

Also inBrowser
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.