diff options
author | reuixiy <reuixiy@gmail.com> | 2021-05-24 18:26:29 +0300 |
---|---|---|
committer | reuixiy <reuixiy@gmail.com> | 2021-05-24 18:26:29 +0300 |
commit | cddaf250b0e93c94697df6de77c873ccbf168c18 (patch) | |
tree | d5a5447044d7716619c3ead6ca94f0faca6fe365 | |
parent | 25be50d1a2d135b7912e6ae8ffc1e46d0acbf2a1 (diff) |
fix: use network first strategy for sw.js
-rw-r--r-- | assets/js/sw.js | 43 |
1 files changed, 24 insertions, 19 deletions
diff --git a/assets/js/sw.js b/assets/js/sw.js index 14ab22c..f812f6c 100644 --- a/assets/js/sw.js +++ b/assets/js/sw.js @@ -6,6 +6,7 @@ 3. https://googlechrome.github.io/samples/service-worker/ 4. https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers 5. https://serviceworke.rs/ + 6. https://www.youtube.com/watch?v=baSiSIyTGSk */ const RUNTIME = 'runtime'; @@ -13,23 +14,27 @@ const RUNTIME = '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; - })() - ); - } + // Do nothing if not the same origin + if (!event.request.url.startsWith(self.location.origin)) { + return; + } + + // Network first strategy + event.respondWith( + (async () => { + const cache = await caches.open(RUNTIME); + + try { + const networkResponse = await fetch(event.request); + + await cache.put(event.request, networkResponse.clone()); + + return networkResponse; + } catch (e) { + const cachedResponse = await cache.match(event.request); + + return cachedResponse; + } + })() + ); }); |