From 0f5c2b5c9d5b4deb3c3523a82fecfd2d4f7511ac Mon Sep 17 00:00:00 2001 From: Cotes Chung <11371340+cotes2020@users.noreply.github.com> Date: Tue, 12 May 2020 01:01:12 +0800 Subject: [PATCH] Added exclude list for PWA caching. --- assets/data/cache-list.js | 8 ++++++-- sw.js | 19 ++++++++++++++++--- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/assets/data/cache-list.js b/assets/data/cache-list.js index d06aaba..bbffd7c 100644 --- a/assets/data/cache-list.js +++ b/assets/data/cache-list.js @@ -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/' +]; diff --git a/sw.js b/sw.js index 1ed7577..d4f7aba 100644 --- a/sw.js +++ b/sw.js @@ -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) => { - /* console.log('[Service Worker] Caching new resource: ' + e.request.url); */ - cache.put(e.request, response.clone()); + if (!isExcluded(e.request.url)) { + /* console.log('[Service Worker] Caching new resource: ' + e.request.url); */ + cache.put(e.request, response.clone()); + } return response; }); });