Skip to content

Instantly share code, notes, and snippets.

@user890104
Last active July 21, 2018 20:28
Show Gist options
  • Save user890104/be4a393c41e14ad6f06acce64408de75 to your computer and use it in GitHub Desktop.
Save user890104/be4a393c41e14ad6f06acce64408de75 to your computer and use it in GitHub Desktop.
Service worker with cache
const cacheId = 'cache-v1';
function fetchAndCache(request, cache) {
return fetch(request).then(function(response) {
return cache.put(request, response.clone()).then(function() {
return response;
});
});
}
self.addEventListener('fetch', function(event) {
// This prevents some weird issue with Chrome DevTools and 'only-if-cached'
// Fixes issue #385, also ref to:
// - https://github.com/paulirish/caltrainschedule.io/issues/49
// - https://bugs.chromium.org/p/chromium/issues/detail?id=823392
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
return;
}
if (event.request.method !== 'GET') {
return;
}
const url = new URL(event.request.url);
if (url.protocol !== 'https:') {
return;
}
if (url.origin !== location.origin) {
return;
}
event.respondWith(
caches.open(cacheId).then(function(cache) {
return cache.match(event.request).then(function(response) {
if (response) {
event.waitUntil(
fetchAndCache(event.request, cache)
);
return response;
}
return fetchAndCache(event.request, cache);
});
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment