This commit is contained in:
Adler Neves 2019-12-30 11:38:26 -03:00
parent 5d8562bda8
commit 99eaa986fe

View File

@ -12,47 +12,38 @@ var urlsToCache = [
'./font-awesome-4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0' './font-awesome-4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0'
]; ];
self.addEventListener('install', function (event) { self.addEventListener('install', event => {
// Perform install steps // Perform install steps
event.waitUntil( event.waitUntil(
caches.open(CACHE_NAME) caches.open(CACHE_NAME)
.then(function (cache) { .then(cache => {
console.log('Opened cache'); console.log('Opened cache');
return cache.addAll(urlsToCache); return cache.addAll(urlsToCache);
}) })
); );
}); });
self.addEventListener('fetch', function (event) { self.addEventListener('fetch', event => {
event.respondWith( event.respondWith(
caches.match(event.request) fetch(event.request).then(response => {
.then(function (response) { // Throw invalid responses away...
// Cache hit - return response if (!response || response.status !== 200 || response.type !== 'basic')
if (response) { return response;
return response;
}
return fetch(event.request).then( // Cloning the valid reply
function (response) { var responseToCache = response.clone();
// Check if we received a valid response
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// IMPORTANT: Clone the response. A response is a stream // Storing the valid reply; an upsert into the cache
// and because we want the browser to consume the response caches.open(CACHE_NAME).then(cache => {
// as well as the cache consuming the response, we need cache.put(event.request, responseToCache);
// to clone it so we have two streams. });
var responseToCache = response.clone();
caches.open(CACHE_NAME) // Returning the response
.then(function (cache) { return response;
cache.put(event.request, responseToCache); }, () => {
}); // Failed. It's cache or nothing.
return caches.match(event.request);
return response; })
}
);
})
); );
}); });