Skip to content

Commit

Permalink
Testing
Browse files Browse the repository at this point in the history
  • Loading branch information
StrawberryMaster committed Jan 16, 2025
1 parent 84525e0 commit e7725d7
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions service-worker.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const appPrefix = 'TrackGen';
const appVersion = 'v1.0.8';
const appVersion = 'v1.0.9';
const cacheName = `${appPrefix}-${appVersion}`;
const foldersToCache = ['media', 'js', 'css'];
const additionalCache = ['/', 'manifest.json', 'index.html'];
Expand Down Expand Up @@ -34,11 +34,30 @@ async function generateFilesToCache() {
return filesToCache;
}

function isImage(request) {
return request.destination === 'image' || request.url.match(/\.(png|jpg|jpeg|webp|gif)$/i);
}

function isCachable(request) {
const url = new URL(request.url);
return filesToCache && url.origin === location.origin && filesToCache.includes(url.pathname);
}

async function staleWhileRevalidate(request) {
const cache = await caches.open(cacheName);
const cachedResponse = await cache.match(request);

const fetchPromise = fetch(request).then(response => {
if (response.ok) {
cache.put(request, response.clone());
}
console.log(`Updated cache for URL ${request.url}.`);
return response;
});

return cachedResponse || fetchPromise;
}

async function cacheFirstWithRefresh(request) {
try {
const fetchResponsePromise = fetch(request).then(async networkResponse => {
Expand Down Expand Up @@ -75,10 +94,15 @@ self.addEventListener('install', event => {
self.addEventListener("fetch", async (event) => {
const request = event.request;

if (isCachable(request)) {
event.respondWith(cacheFirstWithRefresh(request));
} else {
if (!isCachable(request)) {
event.respondWith(fetch(request));
return;
}

if (isImage(request)) {
event.respondWith(staleWhileRevalidate(request));
} else {
event.respondWith(cacheFirstWithRefresh(request));
}
});

Expand Down

0 comments on commit e7725d7

Please sign in to comment.