diff options
author | Matěj Cepl <mcepl@cepl.eu> | 2019-01-01 12:23:10 +0100 |
---|---|---|
committer | Matěj Cepl <mcepl@cepl.eu> | 2019-01-01 12:29:42 +0100 |
commit | 2cdaf4da73c18d65417cc09bb5e7e3e20a0aa487 (patch) | |
tree | 54092844d57d0c71d44a758ce2f9239aec2a7e09 | |
parent | bbb1185cb77d2c0147cb55ca65b0c46627bee28f (diff) | |
download | hesla-2cdaf4da73c18d65417cc09bb5e7e3e20a0aa487.tar.gz |
Update 2019-01-01; improve fetch handler
Fetch handler from https://github.com/mdn/sw-test/blob/gh-pages/sw.js
-rw-r--r-- | hesla.es | 2 | ||||
-rw-r--r-- | sworker.js | 37 |
2 files changed, 31 insertions, 8 deletions
@@ -95,7 +95,7 @@ export class Hesla extends ActivePage { display() { super.display(); - console.log("cur_watchword = " + this.cur_watchword); + console.log("cur_watchword = " + this.cur_watchword.toISODateString()); document.getElementById(this.cur_watchword.toISODateString()). classList.add("visible"); @@ -1,37 +1,40 @@ -var version = 'v46 - 2018-03-05'; +var VERSION = 'v50 - 2019-01-01'; var toCache = [ '/', - 'index.html', 'activePage.js', 'activePage.js.map', 'config.js', 'config.js.map', + 'favicon.ico', 'hesla.js', 'hesla.js.map', 'hesla.webapp', - 'favicon.ico', 'icon-128.png', 'icon-30.png', 'icon-60.png', 'index_de.html', + 'index.html', 'require.js', 'screen.css' ]; self.addEventListener('install', event => { + console.log('install version = ' + VERSION); event.waitUntil( - caches.open('static' + version) + caches.open(VERSION) .then( c => c.addAll(toCache) - .then(v => console.log('Yay!'), e => console.log('Error')) + .then(v => console.log('Yay!' + VERSION), e => console.log('Error')) ) ); }); self.addEventListener('activate', event => { + console.log('activate version = ' + VERSION); + console.log('keys:\n' + caches.keys()); event.waitUntil(caches.keys().then( keys => Promise.all( - keys.filter(key => key != 'static' + version). + keys.filter(key => key != VERSION). map(key => caches.delete(key)) ) ) @@ -39,5 +42,25 @@ self.addEventListener('activate', event => { }); self.addEventListener('fetch', function(event) { - event.respondWith(caches.match(event.request)); + event.respondWith(caches.match(event.request).then(function(response) { + // caches.match() always resolves + // but in case of success response will have value + if (response !== undefined) { + return response; + } else { + 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(VERSION).then(function (cache) { + cache.put(event.request, responseClone); + }); + return response; + }).catch(function () { + return caches.match('/sw-test/gallery/myLittleVader.jpg'); + }); + } + })); }); |