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 => {
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);
});
}));
}
});