Files
darkshy.bronyfurry.com/sw.js
2023-01-14 02:33:38 +03:00

51 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
self.addEventListener('install', (event) => {
console.log('Установлен');
});
self.addEventListener('activate', (event) => {
console.log('Активирован');
});
self.addEventListener('fetch', (event) => {
console.log('Происходит запрос на сервер');
});
const CACHE = 'network-or-cache-v1';
const timeout = 400;
// При установке воркера мы должны закешировать часть данных (статику).
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE).then((cache) => cache.addAll([
'/img/favicon.ico',
'/css/style.css'
])
));
});
// при событии fetch, мы и делаем запрос, но используем кэш, только после истечения timeout.
self.addEventListener('fetch', (event) => {
event.respondWith(fromNetwork(event.request, timeout)
.catch((err) => {
console.log(`Error: ${err.message()}`);
return fromCache(event.request);
}));
});
// Временно-ограниченный запрос.
function fromNetwork(request, timeout) {
return new Promise((fulfill, reject) => {
var timeoutId = setTimeout(reject, timeout);
fetch(request).then((response) => {
clearTimeout(timeoutId);
fulfill(response);
}, reject);
});
}
function fromCache(request) {
// Открываем наше хранилище кэша (CacheStorage API), выполняем поиск запрошенного ресурса.
// Обратите внимание, что в случае отсутствия соответствия значения Promise выполнится успешно, но со значением `undefined`
return caches.open(CACHE).then((cache) =>
cache.match(request).then((matching) =>
matching || Promise.reject('no-match')
));
}