From 99eaa986fe8f6aa3a088004732d4039d2e216749 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81dler=20Neves?= Date: Mon, 30 Dec 2019 11:38:26 -0300 Subject: [PATCH] update --- html/sw.js | 49 ++++++++++++++++++++----------------------------- 1 file changed, 20 insertions(+), 29 deletions(-) diff --git a/html/sw.js b/html/sw.js index 51789b9..c3c0d13 100644 --- a/html/sw.js +++ b/html/sw.js @@ -12,47 +12,38 @@ var urlsToCache = [ './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 event.waitUntil( caches.open(CACHE_NAME) - .then(function (cache) { + .then(cache => { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); -self.addEventListener('fetch', function (event) { +self.addEventListener('fetch', event => { event.respondWith( - caches.match(event.request) - .then(function (response) { - // Cache hit - return response - if (response) { - return response; - } + fetch(event.request).then(response => { + // Throw invalid responses away... + if (!response || response.status !== 200 || response.type !== 'basic') + return response; - return fetch(event.request).then( - function (response) { - // Check if we received a valid response - if (!response || response.status !== 200 || response.type !== 'basic') { - return response; - } + // Cloning the valid reply + var responseToCache = response.clone(); - // IMPORTANT: Clone the response. A response is a stream - // and because we want the browser to consume the response - // as well as the cache consuming the response, we need - // to clone it so we have two streams. - var responseToCache = response.clone(); + // Storing the valid reply; an upsert into the cache + caches.open(CACHE_NAME).then(cache => { + cache.put(event.request, responseToCache); + }); - caches.open(CACHE_NAME) - .then(function (cache) { - cache.put(event.request, responseToCache); - }); - - return response; - } - ); - }) + // Returning the response + return response; + }, () => { + // Failed. It's cache or nothing. + return caches.match(event.request); + }) ); }); +