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.
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.
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;
}),
);
});first visit: GET /app.css -> network (stored in assets-v1)
second visit: GET /app.css -> served from cache, refreshed in the backgroundresponse.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.