Add sitemap support and enhance service worker caching strategy

This commit is contained in:
Florian Weber 2025-03-20 11:30:27 +01:00
parent f915dad908
commit 63de9a9476
Signed by: f.weber
GPG Key ID: A1C85EB19014A2D3
2 changed files with 45 additions and 4 deletions

View File

@ -5,6 +5,7 @@ permalink: /assets/js/service-worker.js
const CACHE_NAME = "cyberpunk-cache-v1";
const OFFLINE_URL = "/offline.html"; // Diese Seite wird angezeigt, wenn offline
const BASE_PATH = "{{ "/" | relative_url }}";
const SITEMAP_URL = BASE_PATH + "sitemap.json";
const urlsToCache = [
BASE_PATH,
@ -34,7 +35,9 @@ const urlsToCache = [
BASE_PATH + "/assets/game-data/characters/carver.json",
];
// Installations-Event: Dateien werden in den Cache geladen
/**
* Install-Event: Cache Standarddateien
*/
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
@ -43,18 +46,45 @@ self.addEventListener("install", (event) => {
);
});
// Fetch-Event: Prüft, ob eine Datei im Cache ist, bevor sie aus dem Netz geladen wird
/**
* Fetch-Event: Cache-First Strategie mit Offline-Fallback
*/
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request).catch(() => {
return caches.match(OFFLINE_URL); // Falls offline, lade offline.html
return caches.match(OFFLINE_URL);
});
})
);
});
// Aktivierungs-Event: Löscht alten Cache, wenn sich Dateien geändert haben
/**
* Wenn die Startseite geladen wird, lade automatisch alle Seiten aus der Sitemap in den Cache
*/
self.addEventListener("sync", (event) => {
if (event.tag === "cache-all-pages") {
event.waitUntil(
fetch(SITEMAP_URL)
.then((response) => response.json())
.then((data) => {
return caches.open(CACHE_NAME).then((cache) => {
return Promise.all(
data.pages.map((page) => {
return fetch(page.url)
.then((response) => cache.put(page.url, response))
.catch((err) => console.error("Fehler beim Cachen:", err));
})
);
});
})
);
}
});
/**
* Aktivierungs-Event: Löscht alten Cache
*/
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {

11
sitemap.json.html Normal file
View File

@ -0,0 +1,11 @@
---
permalink: /sitemap.json
---
{
"pages": [
{% for page in site.pages %}
{ "url": "{{ page.url | relative_url }}" }{% unless forloop.last %},{% endunless %}
{% endfor %}
]
}