2026-08-30 23:34:45 +02:00
|
|
|
const CACHE_VERSION = "3";
|
2024-07-07 16:56:12 +02:00
|
|
|
|
2024-08-02 13:55:20 +02:00
|
|
|
self.addEventListener("fetch", (event) => {
|
2026-04-01 08:46:10 +00:00
|
|
|
event.respondWith(handleRequest(event));
|
2024-08-02 13:55:20 +02:00
|
|
|
});
|
2024-07-07 16:56:12 +02:00
|
|
|
|
2024-08-02 13:55:20 +02:00
|
|
|
async function handleRequest(event) {
|
2026-04-01 08:46:10 +00:00
|
|
|
const response = await getFromCache(event);
|
|
|
|
|
if (response) {
|
|
|
|
|
fetchAndCache(event); // Call this but don't await, allowing the cache to update in the background
|
|
|
|
|
return response;
|
|
|
|
|
}
|
|
|
|
|
return fetchAndCache(event);
|
2024-07-07 16:56:12 +02:00
|
|
|
}
|
|
|
|
|
|
2024-08-02 13:55:20 +02:00
|
|
|
async function getFromCache(event) {
|
2026-04-01 08:46:10 +00:00
|
|
|
const request = event.request;
|
|
|
|
|
const cache = await caches.open(CACHE_VERSION);
|
|
|
|
|
const response = await cache.match(request);
|
|
|
|
|
return response;
|
2024-07-07 16:56:12 +02:00
|
|
|
}
|
|
|
|
|
|
2024-08-02 13:55:20 +02:00
|
|
|
async function fetchAndCache(event) {
|
2026-04-01 08:46:10 +00:00
|
|
|
const request = event.request;
|
2026-08-30 23:34:45 +02:00
|
|
|
const response = await fetch(request, {cache: "no-cache"});
|
2026-04-01 08:46:10 +00:00
|
|
|
if (response.status === 200) {
|
|
|
|
|
// Only cache successful responses
|
|
|
|
|
const cache = await caches.open(CACHE_VERSION);
|
|
|
|
|
cache.put(request, response.clone());
|
|
|
|
|
}
|
|
|
|
|
return response;
|
2024-07-07 16:56:12 +02:00
|
|
|
}
|