Skip to content

Instantly share code, notes, and snippets.

@tjoskar
Last active March 13, 2017 17:45
Show Gist options
  • Save tjoskar/3c9af0f405d01c69449315a2cfeb2f33 to your computer and use it in GitHub Desktop.
Save tjoskar/3c9af0f405d01c69449315a2cfeb2f33 to your computer and use it in GitHub Desktop.
networkFallbackOnCache
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