Skip to content

Instantly share code, notes, and snippets.

@jeffposnick
Created April 5, 2019 19:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeffposnick/73f071ffeacecfe60e12501100f6003c to your computer and use it in GitHub Desktop.
Save jeffposnick/73f071ffeacecfe60e12501100f6003c to your computer and use it in GitHub Desktop.
addEventListener('install', (event) => ; {
event.waitUntil(async function() {
const cache = await caches.open('static-v1');
await cache.addAll(['offline.html', 'styles.css']);
}());
});
// See https://developers.google.com/web/updates/2017/02/navigation-preload#activating_navigation_preload
addEventListener('activate', event => {
event.waitUntil(async function() {
// Feature-detect
if (self.registration.navigationPreload) {
// Enable navigation preloads!
await self.registration.navigationPreload.enable();
}
}());
});
addEventListener('fetch', (event) => {
const { request } = event;
// Always bypass for range requests, due to browser bugs
if (request.headers.has('range')) return;
event.respondWith(async function() {
// Try to get from the cache:
const cachedResponse = await caches.match(request);
if (cachedResponse) return cachedResponse;
try {
// See https://developers.google.com/web/updates/2017/02/navigation-preload#using_the_preloaded_response
const response = await event.preloadResponse;
if (response) return response;
// Otherwise, get from the network
return await fetch(request);
} catch (err) {
// If this was a navigation, show the offline page:
if (request.mode === 'navigate') {
return caches.match('offline.html');
}
// Otherwise throw
throw err;
}
}());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment