From 543a1ed63f556f02b3933cb5b7710f60a62dacb7 Mon Sep 17 00:00:00 2001 From: Santiago Lo Coco Date: Sat, 18 May 2024 22:56:37 +0200 Subject: [PATCH] Add service-worker.js --- src/service-worker.js | 66 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/service-worker.js diff --git a/src/service-worker.js b/src/service-worker.js new file mode 100644 index 0000000..f03122d --- /dev/null +++ b/src/service-worker.js @@ -0,0 +1,66 @@ +/// +import { build, files, version } from "$service-worker" + +const CACHE = `cache-${version}` + +const ASSETS = [...build, ...files] + +self.addEventListener("install", (event) => { + async function addFilesToCache() { + const cache = await caches.open(CACHE) + await cache.addAll(ASSETS) + } + + event.waitUntil(addFilesToCache()) +}) + +self.addEventListener("activate", (event) => { + async function deleteOldCaches() { + for (const key of await caches.keys()) { + if (key !== CACHE) await caches.delete(key) + } + } + + event.waitUntil(deleteOldCaches()) +}) + +self.addEventListener("fetch", (event) => { + if (event.request.method !== "GET") return + + async function respond() { + const url = new URL(event.request.url) + const cache = await caches.open(CACHE) + + if (ASSETS.includes(url.pathname)) { + const response = await cache.match(url.pathname) + + if (response) { + return response + } + } + + try { + const response = await fetch(event.request) + + if (!(response instanceof Response)) { + throw new Error("invalid response from fetch") + } + + if (response.status === 200) { + cache.put(event.request, response.clone()) + } + + return response + } catch (err) { + const response = await cache.match(event.request) + + if (response) { + return response + } + + throw err + } + } + + event.respondWith(respond()) +})