diff options
author | jakob.stendahl <jakob.stendahl@infomedia.dk> | 2023-01-15 22:35:42 +0100 |
---|---|---|
committer | Jakob Stendahl <jakob.stendahl@outlook.com> | 2023-01-15 22:35:42 +0100 |
commit | 3df1a8049dc693fb1a8835d2aafdd57b74aac407 (patch) | |
tree | 82b34456f34224a92f36591be908c69a4fddb3eb /src/service-worker.js | |
parent | 216e1259c32c4775768da915b6fea9b8adc5c35f (diff) | |
download | microbit-gamepad-3df1a8049dc693fb1a8835d2aafdd57b74aac407.tar.gz microbit-gamepad-3df1a8049dc693fb1a8835d2aafdd57b74aac407.zip |
Initial commit
Diffstat (limited to 'src/service-worker.js')
-rw-r--r-- | src/service-worker.js | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/src/service-worker.js b/src/service-worker.js new file mode 100644 index 0000000..96accb3 --- /dev/null +++ b/src/service-worker.js @@ -0,0 +1,55 @@ +var APP_PREFIX = 'hoverbitcontroller' // Identifier for this app (this needs to be consistent across every cache update) +var VERSION = '{{ VERSION }}' // Version of the off-line cache (change this value everytime you want to update cache) +var CACHE_NAME = APP_PREFIX + VERSION +var URLS = ["{{ CACHE_FILES }}"] // This will be replaced by the deploy-script + +// Respond with cached resources +self.addEventListener('fetch', function (e) { + console.log('fetch request : ' + e.request.url) + e.respondWith( + caches.match(e.request).then(function (request) { + if (request) { // if cache is available, respond with cache + console.log('responding with cache : ' + e.request.url) + return request + } else { // if there are no cache, try fetching request + console.log('file is not cached, fetching : ' + e.request.url) + return fetch(e.request) + } + + // You can omit if/else for console.log & put one line below like this too. + // return request || fetch(e.request) + }) + ) +}) + +// Cache resources +self.addEventListener('install', function (e) { + e.waitUntil( + caches.open(CACHE_NAME).then(function (cache) { + console.log('installing cache : ' + CACHE_NAME) + return cache.addAll(URLS) + }) + ) +}) + +// Delete outdated caches +self.addEventListener('activate', function (e) { + e.waitUntil( + caches.keys().then(function (keyList) { + // `keyList` contains all cache names under your username.github.io + // filter out ones that has this app prefix to create white list + var cacheWhitelist = keyList.filter(function (key) { + return key.indexOf(APP_PREFIX) + }) + // add current cache name to white list + cacheWhitelist.push(CACHE_NAME) + + return Promise.all(keyList.map(function (key, i) { + if (cacheWhitelist.indexOf(key) === -1) { + console.log('deleting cache : ' + keyList[i] ) + return caches.delete(keyList[i]) + } + })) + }) + ) +}) |