reduce noise

This commit is contained in:
Lee Salminen 2022-07-04 14:17:46 -06:00
parent b298e12cd3
commit 52b8506d0a

View file

@ -12,7 +12,7 @@ self.addEventListener('activate', evt =>
caches.keys().then(cacheNames => { caches.keys().then(cacheNames => {
return Promise.all( return Promise.all(
cacheNames.map(cacheName => { cacheNames.map(cacheName => {
const currentCacheVersion = cacheName.split('-').slice(-2) const currentCacheVersion = cacheName.split('-').slice(-2, 2)
if (currentCacheVersion !== CACHE_VERSION) { if (currentCacheVersion !== CACHE_VERSION) {
return caches.delete(cacheName); return caches.delete(cacheName);
} }
@ -22,40 +22,24 @@ self.addEventListener('activate', evt =>
) )
); );
// fetch the resource from the network // The fetch handler serves responses for same-origin resources from a cache.
const fromNetwork = (request, timeout) => // If no response is found, it populates the runtime cache with the response
new Promise((fulfill, reject) => { // from the network before returning it to the page.
const timeoutId = setTimeout(reject, timeout); self.addEventListener('fetch', event => {
fetch(request).then(response => { // Skip cross-origin requests, like those for Google Analytics.
clearTimeout(timeoutId); if (event.request.url.startsWith(self.location.origin) && event.request.method == "GET") {
fulfill(response);
update(request);
}, reject);
});
// fetch the resource from the browser cache // Open the cache
const fromCache = request => event.respondWith(caches.open(CURRENT_CACHE + getApiKey(event.request)).then((cache) => {
caches // Go to the network first
.open(CURRENT_CACHE + getApiKey(request)) return fetch(event.request).then((fetchedResponse) => {
.then(cache => cache.put(event.request, fetchedResponse.clone());
cache
.match(request)
.then(matching => matching || cache.match('/offline/'))
);
// cache the current page to make it available for offline return fetchedResponse;
const update = request => }).catch(() => {
caches // If the network is unavailable, get
.open(CURRENT_CACHE + getApiKey(request)) return cache.match(event.request.url);
.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));
}); });