Created
April 5, 2019 19:33
-
-
Save jeffposnick/73f071ffeacecfe60e12501100f6003c to your computer and use it in GitHub Desktop.
https://paul.kinlan.me/offline-fallback-page-with-service-worker/, with navigation preload
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
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