aboutsummaryrefslogtreecommitdiff
path: root/public/service-worker.js
diff options
context:
space:
mode:
authoreug-vs <eug-vs@keemail.me>2020-08-24 21:09:17 +0300
committereug-vs <eug-vs@keemail.me>2020-08-24 21:09:17 +0300
commit918d2f62a9589abc657d9aa6c458f4630ecb5a41 (patch)
tree20bbefd3e380df863af392d87507286743d52ee4 /public/service-worker.js
parent89f038c7a0ccf6de94516cba8499a0bc69f8dae1 (diff)
downloadwhich-ui-918d2f62a9589abc657d9aa6c458f4630ecb5a41.tar.gz
feat: implement service-worker with caching
Diffstat (limited to 'public/service-worker.js')
-rw-r--r--public/service-worker.js53
1 files changed, 53 insertions, 0 deletions
diff --git a/public/service-worker.js b/public/service-worker.js
new file mode 100644
index 0000000..d2c6b9e
--- /dev/null
+++ b/public/service-worker.js
@@ -0,0 +1,53 @@
+const CACHE_NAME = 'v1.2.4'; // Per-version requests cache
+const IMAGES_CACHE_NAME = 'images' // Long-term images cache
+
+const isS3Url = url => url.includes('amazonaws.com');
+
+this.addEventListener('install', event => {
+ event.waitUntil(
+ caches.open(CACHE_NAME)
+ .then(cache => cache.addAll(['index.html']))
+ .catch(e => console.log(e))
+ );
+})
+
+this.addEventListener('fetch', event => {
+ if (isS3Url(event.request.url)) {
+ event.respondWith(
+ caches.open(IMAGES_CACHE_NAME)
+ .then(cache => cache.match(event.request)
+ .then(match => match || fetch(event.request)
+ .then(response => {
+ cache.put(event.request, response.clone());
+ return response;
+ })
+ )
+ .catch(e => console.log(`Error ${e}`))
+ )
+ );
+ } else {
+ event.respondWith(
+ caches.open(CACHE_NAME)
+ .then(cache => fetch(event.request)
+ .then(response => {
+ cache.put(event.request, response.clone());
+ return response;
+ })
+ .catch(() => cache.match(event.request))
+ )
+ );
+ }
+});
+
+this.addEventListener('activate', event => {
+ const cacheWhiteList = [CACHE_NAME, IMAGES_CACHE_NAME];
+ event.waitUntil(
+ caches.keys()
+ .then(keys => Promise.all(
+ keys.map(key => {
+ if (cacheWhiteList.indexOf(key) === -1) return caches.delete(key);
+ })
+ ))
+ );
+});
+