Files
CT/dist/sw.js
T

32 lines
873 B
JavaScript
Raw Normal View History

2024-08-02 13:55:20 +02:00
const CACHE_VERSION = "v2";
2024-07-07 16:56:12 +02:00
2024-08-02 13:55:20 +02:00
self.addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event));
});
2024-07-07 16:56:12 +02:00
2024-08-02 13:55:20 +02:00
async function handleRequest(event) {
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;
2024-07-07 16:56:12 +02:00
}
2024-08-02 13:55:20 +02:00
return fetchAndCache(event);
2024-07-07 16:56:12 +02:00
}
2024-08-02 13:55:20 +02:00
async function getFromCache(event) {
2024-07-07 16:56:12 +02:00
const request = event.request;
const cache = await caches.open(CACHE_VERSION);
2024-08-02 13:55:20 +02:00
const response = await cache.match(request);
2024-07-07 16:56:12 +02:00
return response;
}
2024-08-02 13:55:20 +02:00
async function fetchAndCache(event) {
2024-07-07 16:56:12 +02:00
const request = event.request;
2024-08-02 13:55:20 +02:00
const response = await fetch(request);
if (response.status === 200) { // Only cache successful responses
const cache = await caches.open(CACHE_VERSION);
cache.put(request, response.clone());
}
2024-07-07 16:56:12 +02:00
return response;
}