From 52b8506d0a1a2013dc334e9f6cccecbef687a905 Mon Sep 17 00:00:00 2001 From: Lee Salminen Date: Mon, 4 Jul 2022 14:17:46 -0600 Subject: [PATCH] reduce noise --- lnbits/core/static/js/service-worker.js | 54 +++++++++---------------- 1 file changed, 19 insertions(+), 35 deletions(-) diff --git a/lnbits/core/static/js/service-worker.js b/lnbits/core/static/js/service-worker.js index c8b7a7a1..4f0addc2 100644 --- a/lnbits/core/static/js/service-worker.js +++ b/lnbits/core/static/js/service-worker.js @@ -12,7 +12,7 @@ self.addEventListener('activate', evt => caches.keys().then(cacheNames => { return Promise.all( cacheNames.map(cacheName => { - const currentCacheVersion = cacheName.split('-').slice(-2) + const currentCacheVersion = cacheName.split('-').slice(-2, 2) if (currentCacheVersion !== CACHE_VERSION) { return caches.delete(cacheName); } @@ -22,40 +22,24 @@ self.addEventListener('activate', evt => ) ); -// fetch the resource from the network -const fromNetwork = (request, timeout) => - new Promise((fulfill, reject) => { - const timeoutId = setTimeout(reject, timeout); - fetch(request).then(response => { - clearTimeout(timeoutId); - fulfill(response); - update(request); - }, reject); - }); +// The fetch handler serves responses for same-origin resources from a cache. +// If no response is found, it populates the runtime cache with the response +// from the network before returning it to the page. +self.addEventListener('fetch', event => { + // Skip cross-origin requests, like those for Google Analytics. + if (event.request.url.startsWith(self.location.origin) && event.request.method == "GET") { -// fetch the resource from the browser cache -const fromCache = request => - caches - .open(CURRENT_CACHE + getApiKey(request)) - .then(cache => - cache - .match(request) - .then(matching => matching || cache.match('/offline/')) - ); + // Open the cache + event.respondWith(caches.open(CURRENT_CACHE + getApiKey(event.request)).then((cache) => { + // Go to the network first + return fetch(event.request).then((fetchedResponse) => { + cache.put(event.request, fetchedResponse.clone()); -// cache the current page to make it available for offline -const update = request => - caches - .open(CURRENT_CACHE + getApiKey(request)) - .then(cache => - fetch(request).then(response => cache.put(request, response)) - ); - -// general strategy when making a request (eg if online try to fetch it -// from the network with a timeout, if something fails serve from cache) -self.addEventListener('fetch', evt => { - evt.respondWith( - fromNetwork(evt.request, 10000).catch(() => fromCache(evt.request)) - ); - evt.waitUntil(update(evt.request)); + return fetchedResponse; + }).catch(() => { + // If the network is unavailable, get + return cache.match(event.request.url); + }); + })); + } }); \ No newline at end of file