more readability: use fetch and cache
This commit is contained in:
parent
c208c7415b
commit
62d58f9059
26
cachersw.js
26
cachersw.js
@ -52,9 +52,8 @@ self.addEventListener('install', (event) => {
|
|||||||
*
|
*
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
/*
|
|
||||||
self.fetch_and_cache = function (evreq) {
|
self.fetch_and_cache = function (evreq) {
|
||||||
fetch(evreq).then((response) => {
|
return fetch(evreq).then((response) => {
|
||||||
return caches.open('v1').then((cache) => {
|
return caches.open('v1').then((cache) => {
|
||||||
console.log('fetch and cache ' + evreq);
|
console.log('fetch and cache ' + evreq);
|
||||||
cache.put(evreq, response.clone());
|
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) {
|
event.respondWith(caches.match(event.request).then(function(cachedResponse) {
|
||||||
// caches.match() always resolves
|
// caches.match() always resolves
|
||||||
// but in case of success response will have value
|
// but in case of success response will have value
|
||||||
if (cachedResponse !== undefined)
|
if (cachedResponse !== undefined)
|
||||||
return cachedResponse;
|
return cachedResponse;
|
||||||
return fetch(event.request).then(function (response) {
|
return self.fetch_and_cache(event.request)
|
||||||
// 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;
|
|
||||||
});
|
|
||||||
}));
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
Loading…
Reference in New Issue
Block a user