Skip to content

Instantly share code, notes, and snippets.

@surma
Last active April 8, 2024 22:38
Show Gist options
  • Save surma/eb441223daaedf880801ad80006389f1 to your computer and use it in GitHub Desktop.
Save surma/eb441223daaedf880801ad80006389f1 to your computer and use it in GitHub Desktop.
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.
event.respondWith(
Promise.race([fetched.catch(_ => cached), cached])
.then(resp => resp || fetched)
.catch(_ => new Response(null, {status: 404}))
);
// Update the cache with the version we fetched
event.waitUntil(
Promise.all([fetchedCopy, caches.open('cache-v1')])
.then(([response, cache]) => cache.put(event.request, response))
.catch(_ => {/* eat any errors */})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment