Created
March 1, 2021 07:03
-
-
Save joshuacerbito/b6b1424a2e214a85f1bd99a02ccf54dd to your computer and use it in GitHub Desktop.
Simple Caching Strategy for Service Workers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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