This commit is contained in:
“bobbydigitales”
2023-11-09 21:45:17 -08:00
parent eb15d37527
commit 148df433c4
15 changed files with 961016 additions and 295 deletions

72
src/sw.ts Normal file
View File

@@ -0,0 +1,72 @@
// Establish a cache name
const cacheName = "dandelion_cache_v1";
const contentToCache = [
"/index.html",
"/main.js",
"/marked.min.js",
"/db.js",
"/bookerly.woff2",
"/virgil.woff2",
"/favicon.ico"
];
self.addEventListener("install", (e:any) => {
e.waitUntil(
(async () => {
const cache = await caches.open(cacheName);
console.log(
"[Service Worker] Caching all: app shell and content",
contentToCache
);
await cache.addAll(contentToCache);
})()
);
});
self.addEventListener("fetch", (e:any) => {
e.respondWith(
(async () => {
const r = await caches.match(e.request);
if (r) {
console.log(
`[Service Worker] Cache hit for resource: ${e.request.url}`
);
return r;
}
let response;
try {
console.log(
`[Service Worker] Cache miss, attempting to fetch resource: ${e.request.url}`
);
response = await fetch(e.request);
} catch (e) {
console.warn(e);
}
const cache = await caches.open(cacheName);
console.log(
`[Service Worker] Adding resource to cache: ${e.request.url}`
);
if (!response) {
throw new Error(`Failed to fetch resource: ${e.request.url}`)
}
cache.put(e.request, response.clone());
return response;
})()
);
});
addEventListener("message", async (e) => {
console.log(`Message received: ${e.data}`);
switch (e.data.type) {
case "updateMain":
const cache = await caches.open(cacheName);
console.log(`[Service Worker] Caching new resource: main.js`);
cache.put("/main.js", new Response());
break;
}
});