From 28471e245eed59ebe0d57d7a4f162796eda0943d Mon Sep 17 00:00:00 2001 From: pacien Date: Wed, 24 Oct 2018 04:00:01 +0200 Subject: Switch to cache and update caching strategy --- appcache.js | 38 ++++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/appcache.js b/appcache.js index e4b9bd5..8b117f4 100644 --- a/appcache.js +++ b/appcache.js @@ -42,33 +42,31 @@ class AppCache { "pointless/viewer/screen/timer.js" ]; - const appCache = this; - self.addEventListener("install", function(event) { - event.waitUntil(appCache._onInstall()); - }); + self.addEventListener("install", event => event.waitUntil(this.onInstall())); + self.addEventListener("fetch", event => event.respondWith(this.onFetch(event.request))); + } - self.addEventListener("fetch", function(event) { - event.respondWith(appCache._onFetch(event.request)); - }); + onInstall() { + return caches.open(this.cacheName) + .then(cache => cache.addAll(this.filesToCache)); } - _onInstall() { - const self = this; - return caches.open(this.cacheName).then(function(cache) { - return cache.addAll(self.filesToCache); - }); + onFetch(request) { + return caches.open(this.cacheName) + .then(cache => this._serve(cache, request)); } - _onFetch(request) { - return navigator.onLine ? this._fetchUpdate(request) : caches.match(request); + _serve(cache, request) { + return cache.match(request).then(cachedResponse => { + const update = this._fetchUpdate(cache, request); + return cachedResponse || update; + }); } - _fetchUpdate(request) { - return caches.open(this.cacheName).then(function(cache) { - return fetch(request).then(function(response) { - cache.put(request, response.clone()); - return response; - }); + _fetchUpdate(cache, request) { + return fetch(request).then(networkResponse => { + cache.put(request, networkResponse.clone()); + return networkResponse; }); } } -- cgit v1.2.3