From 97cb67e954e87b7a6dca145fd8b4d7430f2a39f7 Mon Sep 17 00:00:00 2001 From: reuixiy Date: Fri, 16 Apr 2021 11:49:22 +0800 Subject: Revert "fix: Uncaught (in promise) TypeError: Failed to fetch" This reverts commit 5ee69779a3dcd941419110d977c161675abe0132. updates #327 --- assets/js/sw.js | 53 +++++++++++++++++++++-------------------------------- 1 file changed, 21 insertions(+), 32 deletions(-) diff --git a/assets/js/sw.js b/assets/js/sw.js index e738206..14ab22c 100644 --- a/assets/js/sw.js +++ b/assets/js/sw.js @@ -8,39 +8,28 @@ 5. https://serviceworke.rs/ */ -const CACHE_NAME = 'runtime'; +const RUNTIME = 'runtime'; self.skipWaiting(); -self.addEventListener('fetch', function (event) { - // Do nothing if not from the same origin - if (!event.request.url.startsWith(self.location.origin)) return; - - event.respondWith( - caches.match(event.request).then(function (response) { - // Cache hit - return response - if (response) { - return response; - } - - return fetch(event.request).then(function (response) { - // Check if we received a valid response - if (!response || response.status !== 200 || response.type !== 'basic') { - return response; - } - - // IMPORTANT: Clone the response. A response is a stream - // and because we want the browser to consume the response - // as well as the cache consuming the response, we need - // to clone it so we have two streams. - var responseToCache = response.clone(); - - caches.open(CACHE_NAME).then(function (cache) { - cache.put(event.request, responseToCache); - }); - - return response; - }); - }) - ); +self.addEventListener('fetch', (event) => { + if (event.request.url.startsWith(self.location.origin)) { + event.respondWith( + (async () => { + const cache = await caches.open(RUNTIME); + const cachedResponse = await cache.match(event.request); + const networkResponsePromise = fetch(event.request); + + event.waitUntil( + (async () => { + const networkResponse = await networkResponsePromise; + await cache.put(event.request, networkResponse.clone()); + })() + ); + + // Returned the cached response if we have one, otherwise return the network response. + return cachedResponse || networkResponsePromise; + })() + ); + } }); -- cgit v1.2.3