|
|
const CACHE_NAME = 'teplostil-cache-v5'; |
|
|
const URLS_TO_CACHE = [ |
|
|
'/', |
|
|
'/index.html', |
|
|
'/style.css', |
|
|
'/icon.png', |
|
|
'/icon-512x512.png', |
|
|
'/manifest.json' |
|
|
]; |
|
|
|
|
|
|
|
|
self.addEventListener('install', (event) => { |
|
|
event.waitUntil( |
|
|
caches.open(CACHE_NAME).then((cache) => { |
|
|
console.log('Opened cache'); |
|
|
return cache.addAll(URLS_TO_CACHE); |
|
|
}) |
|
|
); |
|
|
self.skipWaiting(); |
|
|
}); |
|
|
|
|
|
|
|
|
self.addEventListener('activate', (event) => { |
|
|
event.waitUntil( |
|
|
caches.keys().then((cacheNames) => { |
|
|
return Promise.all( |
|
|
cacheNames.map((cacheName) => { |
|
|
if (cacheName !== CACHE_NAME) { |
|
|
console.log('Deleting old cache:', cacheName); |
|
|
return caches.delete(cacheName); |
|
|
} |
|
|
}) |
|
|
); |
|
|
}) |
|
|
); |
|
|
self.clients.claim(); |
|
|
}); |
|
|
|
|
|
|
|
|
self.addEventListener('fetch', (event) => { |
|
|
const requestUrl = new URL(event.request.url); |
|
|
|
|
|
|
|
|
if (requestUrl.origin !== self.location.origin) { |
|
|
console.log('Пропускаем внешний запрос (не кэшируем через SW):', requestUrl.href); |
|
|
|
|
|
return; |
|
|
} |
|
|
|
|
|
|
|
|
if (event.request.mode === 'navigate') { |
|
|
event.respondWith( |
|
|
caches.match('/index.html').then((response) => { |
|
|
return response || fetch(event.request); |
|
|
}) |
|
|
); |
|
|
} else { |
|
|
|
|
|
event.respondWith( |
|
|
caches.match(event.request).then((response) => { |
|
|
|
|
|
if (response) { |
|
|
return response; |
|
|
} |
|
|
|
|
|
|
|
|
return fetch(event.request).then((networkResponse) => { |
|
|
|
|
|
if (requestUrl.origin === self.location.origin) { |
|
|
return caches.open(CACHE_NAME).then((cache) => { |
|
|
cache.put(event.request, networkResponse.clone()); |
|
|
return networkResponse; |
|
|
}); |
|
|
} |
|
|
|
|
|
return networkResponse; |
|
|
}); |
|
|
}).catch(error => { |
|
|
|
|
|
console.error("Fetch failed:", error); |
|
|
|
|
|
return new Response('<h1>Offline</h1><p>Sorry, the content is not available offline.</p>', { |
|
|
headers: { 'Content-Type': 'text/html' } |
|
|
}); |
|
|
|
|
|
}) |
|
|
); |
|
|
} |
|
|
}); |