-
-
Save tjoskar/3c9af0f405d01c69449315a2cfeb2f33 to your computer and use it in GitHub Desktop.
networkFallbackOnCache
This file contains 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 apiCacheName = 'api-cache-v1'; | |
self.addEventListener('fetch', event => { | |
console.log('The user request: ', event.request.url); | |
const url = new URL(event.request.url); | |
if(url.hostname === 'happy-news-nmnepmqeqo.now.sh') { | |
event.respondWith(cacheFallbackOnNetwork(event.request, apiCacheName)); | |
} | |
}); | |
function networkFallbackOnCache(request, cacheName) { | |
return updateCache(request, cacheName) | |
.catch(() => fromCache(request, cacheName)); | |
} | |
async function fromCache(request, cacheName) { | |
const cache = await caches.open(cacheName); | |
return cache.match(request); | |
} | |
async function updateCache(request, cacheName) { | |
const cache = await caches.open(cacheName); | |
const response = await fetch(request); | |
if (response.ok) { | |
await cache.put(request, response.clone()); | |
} | |
return response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment