Skip to content

Instantly share code, notes, and snippets.

@joshuacerbito
Created March 1, 2021 07:03
Show Gist options
  • Save joshuacerbito/b6b1424a2e214a85f1bd99a02ccf54dd to your computer and use it in GitHub Desktop.
Save joshuacerbito/b6b1424a2e214a85f1bd99a02ccf54dd to your computer and use it in GitHub Desktop.
Simple Caching Strategy for Service Workers
const cacheName = 'mycache';
self.onFetch = event => {
const request = event.request;
const networkResponsePromise = fetch(request).catch(_ => {});
const cachedResponsePromise = caches.match(request);
event.respondWith(async function () {
const cacheResponse = await cachedResponsePromise;
if (cacheResponse) return cacheResponse;
const networkResponse = await networkResponsePromise;
if (networkResponse) return networkResponse.clone();
throw new Error(`Neither the network nor the cache has a response for ${request.url}`);
}());
event.waitUntil(async function () {
const networkResponse = await networkResponsePromise;
if (networkResponse) {
const cache = await caches.open(cacheName);
cache.put(request, networkResponse.clone());
}
}());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment