hvvstuhl.de/sw.js
2024-06-09 18:54:55 +02:00

96 lines
No EOL
2.8 KiB
JavaScript

const version = '0.6.2'
const consolePrefix = `[SW v${version}] `
const cacheName = `hvvstuhl-${version}`;
const contentToCache = [
'/',
'/index.html',
'/about.html',
'/main.js',
'/elevators.js',
'/style.css',
'/icons/192.png',
'/icons/512.png',
'/icons/512-maskable.png',
'/icons/512-transparent.png',
'/icons/favicon.ico',
'/icons/favicon.svg',
'/icons/favicon-maskable.svg',
'/icons/favicon-transparent.svg',
'/md_icons/bicycle.svg',
'/md_icons/braille.svg',
'/md_icons/door_sliding.svg',
'/md_icons/elevator.svg',
'/md_icons/elevator-slash.svg',
'/md_icons/fit_width.svg',
'/md_icons/height.svg',
'/md_icons/info.svg',
'/md_icons/load.svg',
'/md_icons/location.svg',
'/md_icons/location-searching.svg',
'/md_icons/speaker.svg',
'/md_icons/up-down.svg',
'/md_icons/wheelchair.svg',
'/md_icons/width.svg',
];
// Service worker Install: Cache all files
self.addEventListener("install", (e) => {
console.log("[Service Worker] Wird installiert....");
e.waitUntil(
(async () => {
const cache = await caches.open(cacheName);
console.log("[Service Worker] Cache wird aufgebaut...");
await cache.addAll(contentToCache);
console.log("[Service Worker] FERTIG");
})(),
);
});
// delete old caches
const deleteCache = async (key) => {
await caches.delete(key);
};
const deleteOldCaches = async () => {
const keyList = await caches.keys();
const cachesToDelete = keyList.filter((key) => key !== cacheName);
await Promise.all(cachesToDelete.map(deleteCache));
};
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
await deleteOldCaches()
await clients.claim();
})(),
);
});
// Respond with data from cache when offline
self.addEventListener("fetch", (e) => {
e.respondWith(
(async () => {
const path = new URL(e.request.url).pathname
if(contentToCache.includes(path)){
console.log(`${consolePrefix}Anfrage: ${path}`);
const r = await caches.match(e.request);
if (r) {
console.log(`${consolePrefix} Im Cache gefunden.`);
return r;
}
const response = await fetch(e.request);
const cache = await caches.open(cacheName);
console.log(`${consolePrefix} Nicht gefunden. Aktualisiere Cache: ${path}`);
await cache.put(e.request, response.clone());
return response;
}else{
console.log(`${consolePrefix}Anfrage übersprungen: ${e.request.url}`);
return await fetch(e.request);
}
})(),
);
});