diff options
| author | Owen Jacobson <owen@grimoire.ca> | 2024-11-11 23:03:41 -0500 |
|---|---|---|
| committer | Owen Jacobson <owen@grimoire.ca> | 2024-11-11 23:03:41 -0500 |
| commit | c6c46436558f5058eccdb9b793ed02fc1640a80d (patch) | |
| tree | 997a94e320aa3ade7caafa23cd01c2d653dcd331 /ui/service-worker.js | |
| parent | a0fc6434cb1f65b558a0a94c5cdddf5d79d15206 (diff) | |
| parent | d5199183bc8114dc78adb19f66b09f1e61c67f1b (diff) | |
Merge remote-tracking branch 'origin/prop/pwa'
Diffstat (limited to 'ui/service-worker.js')
| -rw-r--r-- | ui/service-worker.js | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/ui/service-worker.js b/ui/service-worker.js new file mode 100644 index 0000000..e2143b3 --- /dev/null +++ b/ui/service-worker.js @@ -0,0 +1,54 @@ +/// <reference types="@sveltejs/kit" /> +/// <reference no-default-lib="true"/> +/// <reference lib="esnext" /> +/// <reference lib="webworker" /> + +// Because of this line, this service worker won't run in dev mode in Firefox. +// Only Safari, Edge, Chrome can run it at the moment, because only they +// support modules in service workers. +// +// That's okay! If you run `tools/run` with PILCROW_DEV unset, you will get the +// bundled version, and can work on it. Or just use Safari. +import { build, files, version } from '$service-worker'; + +// Create a unique cache name for this deployment +const CACHE = `cache-${version}`; + +const ASSETS = [ + ...build, // the app itself + ...files // everything in `static` +]; + +self.addEventListener('install', (event) => { + // Create a new cache and add all files to it + async function addFilesToCache() { + const cache = await caches.open(CACHE); + await cache.addAll(ASSETS); + } + + event.waitUntil(addFilesToCache()); +}); + +self.addEventListener('activate', (event) => { + // Remove previous cached data from disk + async function deleteOldCaches() { + for (const key of await caches.keys()) { + if (key !== CACHE) await caches.delete(key); + } + } + + event.waitUntil(deleteOldCaches()); +}); + +// The simplest possible use of the caches above: +async function cacheFirst(request) { + const responseFromCache = await caches.match(request); + if (responseFromCache) { + return responseFromCache; + } + return fetch(request); +}; + +self.addEventListener("fetch", (event) => { + event.respondWith(cacheFirst(event.request)); +}); |
