web/sw.js

61 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-05-09 19:28:18 +03:00
---
layout: compress
2021-01-25 01:20:51 +03:00
# PWA service worker
2020-05-09 19:28:18 +03:00
---
self.importScripts('{{ "/assets/js/data/cache-list.js" | relative_url }}');
2020-05-09 19:28:18 +03:00
var cacheName = 'chirpy-{{ "now" | date: "%Y%m%d.%H%M" }}';
2020-05-11 20:01:12 +03:00
function isExcluded(url) {
const regex = /(^http(s)?|^\/)/; /* the regex for CORS url or relative url */
2020-05-11 20:01:12 +03:00
for (const rule of exclude) {
if (!regex.test(url) ||
url.indexOf(rule) != -1) {
2020-05-11 20:01:12 +03:00
return true;
}
}
return false;
}
2020-05-09 19:28:18 +03:00
self.addEventListener('install', (e) => {
self.skipWaiting();
e.waitUntil(
caches.open(cacheName).then((cache) => {
2020-05-11 20:01:12 +03:00
return cache.addAll(include);
2020-05-09 19:28:18 +03:00
})
);
});
self.addEventListener('fetch', (e) => {
e.respondWith(
caches.match(e.request).then((r) => {
/* console.log(`[sw] method: ${e.request.method}, fetching: ${e.request.url}`); */
2020-05-09 19:28:18 +03:00
return r || fetch(e.request).then((response) => {
return caches.open(cacheName).then((cache) => {
2020-05-11 20:01:12 +03:00
if (!isExcluded(e.request.url)) {
if (e.request.method === "GET") {
/* console.log('[sw] Caching new resource: ' + e.request.url); */
cache.put(e.request, response.clone());
}
2020-05-11 20:01:12 +03:00
}
2020-05-09 19:28:18 +03:00
return response;
});
2020-05-09 19:28:18 +03:00
});
})
);
});
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then((keyList) => {
return Promise.all(keyList.map((key) => {
if(key !== cacheName) {
return caches.delete(key);
}
}));
})
);
});