diff options
author | reuixiy <reuixiy@gmail.com> | 2021-04-13 10:24:48 +0300 |
---|---|---|
committer | reuixiy <reuixiy@gmail.com> | 2021-04-13 10:25:16 +0300 |
commit | 5ee69779a3dcd941419110d977c161675abe0132 (patch) | |
tree | 0e189d65d6467e99c387455ecb91eaedf230f326 | |
parent | 9be741a3238fe5c0d19bc77000057f0a4e1d1181 (diff) |
fix: Uncaught (in promise) TypeError: Failed to fetch
-rw-r--r-- | assets/js/sw.js | 53 |
1 files changed, 32 insertions, 21 deletions
diff --git a/assets/js/sw.js b/assets/js/sw.js index 14ab22c..e738206 100644 --- a/assets/js/sw.js +++ b/assets/js/sw.js @@ -8,28 +8,39 @@ 5. https://serviceworke.rs/ */ -const RUNTIME = 'runtime'; +const CACHE_NAME = 'runtime'; self.skipWaiting(); -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; - })() - ); - } +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; + }); + }) + ); }); |