Added exclude list for PWA caching.

This commit is contained in:
Cotes Chung 2020-05-12 01:01:12 +08:00
parent d8e45694bd
commit 0f5c2b5c9d
2 changed files with 22 additions and 5 deletions

View file

@ -6,7 +6,7 @@
# MIT Licensed
---
var cacheList = [
const include = [
/*--- CSS ---*/
@ -99,7 +99,6 @@ var cacheList = [
/*--- Others ---*/
{% if site.google_analytics.pv.enabled %}
'{{ "/assets/data/pv-data.json" | relative_url }}',
'{{ "/assets/lib/countUp.min.js" | relative_url }}',
'{{ "/assets/js/dist/pageviews.min.js" | relative_url }}',
{% endif %}
@ -110,3 +109,8 @@ var cacheList = [
'{{ "/app.js" | relative_url }}',
'{{ "/sw.js" | relative_url }}'
];
const exclude = [
'/assets/data/pv-data.json',
'/img.shields.io/'
];

15
sw.js
View file

@ -10,11 +10,22 @@ self.importScripts('{{ "/assets/data/cache-list.js" | relative_url }}');
var cacheName = 'chirpy-{{ "now" | date: "%Y%m%d.%H%M" }}';
function isExcluded(url) {
for (const rule of exclude) {
if (url.indexOf(rule) != -1) {
return true;
}
}
return false;
}
self.addEventListener('install', (e) => {
self.skipWaiting();
e.waitUntil(
caches.open(cacheName).then((cache) => {
return cache.addAll(cacheList);
return cache.addAll(include);
})
);
});
@ -26,8 +37,10 @@ self.addEventListener('fetch', (e) => {
/* console.log('[Service Worker] Fetching resource: ' + e.request.url); */
return r || fetch(e.request).then((response) => {
return caches.open(cacheName).then((cache) => {
if (!isExcluded(e.request.url)) {
/* console.log('[Service Worker] Caching new resource: ' + e.request.url); */
cache.put(e.request, response.clone());
}
return response;
});
});