diff --git a/index.html b/index.html index de7fbd5..af56ef6 100644 --- a/index.html +++ b/index.html @@ -28,14 +28,13 @@ \ No newline at end of file diff --git a/js/sw.js b/js/sw.js index 6aee75b..483adaf 100644 --- a/js/sw.js +++ b/js/sw.js @@ -1,15 +1,51 @@ -const CACHE_NAME = 'DarkShy-Cache'; - -// Add whichever assets you want to precache here: -const PRECACHE_ASSETS = [ - '/img/', - '/css/' -] - -// Listener for the install event - precaches our assets list on service worker install. -self.addEventListener('install', event => { - event.waitUntil((async () => { - const cache = await caches.open(CACHE_NAME); - cache.addAll(PRECACHE_ASSETS); - })()); +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') + )); +} \ No newline at end of file