Skip to content

Instantly share code, notes, and snippets.

View lholmquist's full-sized avatar

Lucas Holmquist lholmquist

View GitHub Profile
@surma
surma / staleWhileRevalidate.js
Last active April 8, 2024 22:38
ServiceWorker that implements “Stale-while-revalidate”
// Implements stale-while-revalidate
self.addEventListener('fetch', event => {
const cached = caches.match(event.request);
const fetched = fetch(event.request);
const fetchedCopy = fetched.then(resp => resp.clone());
// Call respondWith() with whatever we get first.
// If the fetch fails (e.g disconnected), wait for the cache.
// If there’s nothing in cache, wait for the fetch.
// If neither yields a response, return a 404.