Update service-worker.js

This commit is contained in:
FURK4NGG
2024-09-30 23:44:52 +03:00
committed by GitHub
parent bf232e6bd9
commit 3edaade34c
+19 -22
View File
@@ -33,8 +33,9 @@ const urlsToCache = [
'/.htaccess.txt' '/.htaccess.txt'
]; ];
const CURRENT_VERSION = 'v1'; const CURRENT_VERSION = 'v2';
// Install event - cache files
self.addEventListener('install', event => { self.addEventListener('install', event => {
event.waitUntil( event.waitUntil(
caches.open(CACHE_NAME) caches.open(CACHE_NAME)
@@ -45,6 +46,7 @@ self.addEventListener('install', event => {
); );
}); });
// Fetch event - serve files from cache if available
self.addEventListener('fetch', event => { self.addEventListener('fetch', event => {
event.respondWith( event.respondWith(
caches.match(event.request).then(response => { caches.match(event.request).then(response => {
@@ -53,26 +55,21 @@ self.addEventListener('fetch', event => {
); );
}); });
// Activate event - update cache if version is different
self.addEventListener('activate', event => { self.addEventListener('activate', event => {
const storedVersion = localStorage.getItem('cache-version'); event.waitUntil(
if (storedVersion !== CURRENT_VERSION) { caches.keys().then(cacheNames => {
console.log(`New version detected: ${CURRENT_VERSION}. Updating cache...`); return Promise.all(
event.waitUntil( cacheNames.map(cacheName => {
caches.keys().then(cacheNames => { if (cacheName !== CACHE_NAME) {
return Promise.all( console.log(`Deleting old cache: ${cacheName}`);
cacheNames.map(cacheName => { return caches.delete(cacheName);
if (cacheName !== CACHE_NAME) { }
console.log(`Deleting old cache: ${cacheName}`); })
return caches.delete(cacheName); );
} }).then(() => {
}) console.log(`Cache updated to version: ${CURRENT_VERSION}`);
); return self.clients.claim(); // Activates the new service worker immediately
}).then(() => { })
localStorage.setItem('cache-version', CURRENT_VERSION); );
console.log(`Cache updated to version: ${CURRENT_VERSION}`);
})
);
} else {
console.log(`Cache version is up-to-date: ${CURRENT_VERSION}`);
}
}); });