2024-04-27 09:37:09 +02:00
|
|
|
const cachables = {
|
|
|
|
"/": "networkFirst",
|
|
|
|
"//": "networkFirst",
|
|
|
|
};
|
|
|
|
|
2024-04-27 10:31:35 +02:00
|
|
|
const checkUrlCaching = (url) => {
|
|
|
|
let caching = (cachables[url] || cachables[`/${url.split('://').slice(1).join('://').split('/')[1]}/`]);
|
|
|
|
if (caching === undefined) {
|
|
|
|
caching = cachables['//'];
|
|
|
|
};
|
|
|
|
return caching;
|
|
|
|
};
|
2024-04-27 09:37:09 +02:00
|
|
|
|
|
|
|
const putResponseInCache = (request, response) => {
|
2024-07-01 20:45:14 +02:00
|
|
|
if (request.method === 'GET' && response.ok) {
|
|
|
|
return caches.open('GamingShitposting/v1').then((cache) => {
|
|
|
|
try {
|
|
|
|
return cache.put(request, response.clone());
|
|
|
|
} catch(err) {}
|
|
|
|
});
|
2024-04-27 09:37:09 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const strategies = {
|
|
|
|
networkFirst: async (request) => {
|
|
|
|
try {
|
|
|
|
const networkResponse = await fetch(request);
|
|
|
|
putResponseInCache(request, networkResponse);
|
|
|
|
return networkResponse;
|
|
|
|
} catch (error) {
|
|
|
|
return ((await caches.match(request)) || Response.error());
|
|
|
|
}
|
|
|
|
},
|
|
|
|
cacheFirst: async (request) => {
|
|
|
|
const fetchResponsePromise = fetch(request).then(async (networkResponse) => {
|
|
|
|
putResponseInCache(request, networkResponse);
|
|
|
|
return networkResponse;
|
|
|
|
});
|
|
|
|
return (await caches.match(request)) || (await fetchResponsePromise);
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
self.addEventListener('activate', () => self.clients.claim());
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
|
|
const strategy = strategies[checkUrlCaching(event.request.url)];
|
|
|
|
if (strategy) {
|
|
|
|
return event.respondWith(strategy(event.request));
|
|
|
|
}
|
2024-07-01 20:45:14 +02:00
|
|
|
});
|