From c7d28e910d9f066df5a93bc0542b5d47428c4b75 Mon Sep 17 00:00:00 2001 From: Elhamne Date: Tue, 21 Feb 2023 22:30:40 +0330 Subject: [PATCH] completed fetch event, #11 --- public/sw.js | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/public/sw.js b/public/sw.js index 0511ed83..ed6420e4 100644 --- a/public/sw.js +++ b/public/sw.js @@ -5,6 +5,7 @@ const dynamicCacheName = 'SAY-dynamic-v1'; const urlsToCache = [ '/', '/index.html', + '/offline.html', '/assets/locales/translations/fa.json', '/assets/locales/translations/en.json', '/images/Say_donation.png', @@ -50,10 +51,10 @@ self.addEventListener('install', (e) => { self.addEventListener('activate', (e) => { // console.log('service worker has been activated'); e.waitUntil( - caches.keys().then((keys) => { + caches.keys().then((keyList) => { return Promise.all( - keys - .filter((key) => key !== staticCacheName) + keyList + .filter((key) => key !== staticCacheName && key !== dynamicCacheName) .map((key) => caches.delete(key)) ); }) @@ -65,14 +66,20 @@ self.addEventListener('fetch', (e) => { // console.log('fetch event', e); e.respondWith( (async () => { - const r = await caches.match(e.request); - if (r) { - return r; + try { + const r = await caches.match(e.request); + if (r) { + return r; + } + const response = await fetch(e.request); + const cache = await caches.open(dynamicCacheName); + await cache.put(e.request.url, response.clone()); + return response; + } catch { + if (e.request.url.indexOf('.html') > -1) { + return caches.match('/offline.html'); + } } - const response = await fetch(e.request); - const cache = await caches.open(dynamicCacheName); - await cache.put(e.request.url, response.clone()); - return response; })() ); });