Last active
December 15, 2021 14:36
-
-
Save acoyfellow/02a5666831402d755ebe8a7ea7bd71b4 to your computer and use it in GitHub Desktop.
Svelte Kit service worker (does not cache external URLs)
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
| import { timestamp, build, files } from '$service-worker'; | |
| const name = `cache-${timestamp}`; | |
| self.addEventListener('install', (event) => { | |
| event.waitUntil(caches.open(name).then((cache) => cache.addAll(['/', ...build, ...files]))); | |
| }); | |
| self.addEventListener('activate', (event) => { | |
| event.waitUntil( | |
| caches.keys().then(async (keys) => { | |
| for (const key of keys) { | |
| if (!key.includes(timestamp)) caches.delete(key); | |
| } | |
| }) | |
| ); | |
| }); | |
| self.addEventListener('fetch', (event) => { | |
| const { request } = event; | |
| if (request.method !== 'GET' || request.headers.has('range')) return; | |
| const url = new URL(request.url); | |
| const cached = caches.match(request); | |
| if (url.origin !== location.origin) return; | |
| // ignore external urls (ie: third party tools) | |
| if (build.includes(url.pathname)) { | |
| // always return build files from cache | |
| event.respondWith(cached); | |
| } else if (url.protocol === 'https:' || location.hostname === 'localhost') { | |
| // hit the network for everything else... | |
| const promise = fetch(request); | |
| promise.then((response) => { | |
| // cache successful responses | |
| if (response.ok && response.type === 'basic') { | |
| const clone = response.clone(); | |
| caches.open(name).then((cache) => { | |
| cache.put(request, clone); | |
| }); | |
| } | |
| }); | |
| // fall back to cache if available | |
| event.respondWith(promise.catch(() => cached || promise)); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment