more readability: use fetch and cache

This commit is contained in:
Amber 2020-11-27 12:12:53 +01:00
parent c208c7415b
commit 62d58f9059
1 changed files with 7 additions and 19 deletions

View File

@ -52,9 +52,8 @@ self.addEventListener('install', (event) => {
*
*
*/
/*
self.fetch_and_cache = function (evreq) {
fetch(evreq).then((response) => {
return fetch(evreq).then((response) => {
return caches.open('v1').then((cache) => {
console.log('fetch and cache ' + evreq);
cache.put(evreq, response.clone());
@ -64,7 +63,6 @@ self.fetch_and_cache = function (evreq) {
});
});
}
*/
/**
*
@ -90,21 +88,11 @@ self.addEventListener('fetch', (event) => {
}
event.respondWith(caches.match(event.request).then(function(cachedResponse) {
// caches.match() always resolves
// but in case of success response will have value
if (cachedResponse !== undefined)
return cachedResponse;
return fetch(event.request).then(function (response) {
// response may be used only once
// we need to save clone to put one copy in cache
// and serve second one
let responseClone = response.clone();
caches.open('v1').then(function (cache) {
cache.put(event.request, responseClone);
});
return response;
});
}));
// caches.match() always resolves
// but in case of success response will have value
if (cachedResponse !== undefined)
return cachedResponse;
return self.fetch_and_cache(event.request)
}));
});