From a2f002dcadd4777049aa7718fbfbb9944c6f0e55 Mon Sep 17 00:00:00 2001 From: Victor Westerlund Date: Mon, 14 Dec 2020 08:01:37 +0100 Subject: [PATCH] Added Service Worker for offline caching Removed Google Analytics script. --- public/index.html | 10 ---------- public/sw.js | 12 +++++++++--- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/public/index.html b/public/index.html index 7cccf4c..f3931c9 100644 --- a/public/index.html +++ b/public/index.html @@ -1,13 +1,6 @@ - - - @@ -17,9 +10,6 @@ Victor Westerlund - - -
diff --git a/public/sw.js b/public/sw.js index f61d9ae..a484376 100644 --- a/public/sw.js +++ b/public/sw.js @@ -9,6 +9,7 @@ self.addEventListener("install", event => { event.waitUntil( caches.open(`content-${version}`).then(cache => cache.addAll([ root, + root + "offline.txt", root + "assets/css/style.css", root + "assets/img/favicon.png", root + "assets/js/script.js", @@ -35,7 +36,7 @@ self.addEventListener("activate", event => { }); // Fetch and save content to bucket -function fetchContent(event) { +async function fetchContent(event) { const networkFetch = fetch(event.request); event.waitUntil( @@ -45,7 +46,8 @@ function fetchContent(event) { }) ); - return caches.match(event.request).then(response => response || networkFetch); + const response = await caches.match(event.request); + return response || networkFetch; } self.addEventListener("fetch", event => { @@ -61,7 +63,11 @@ self.addEventListener("fetch", event => { // Get pattern.gif from generator. Fallback to cache on failure if(origin && url.pathname.endsWith("pattern.gif")) { const pattern = new Request(`${location.origin}/${root}assets/img/pattern.php`); - event.respondWith(fetch(pattern) || caches.match(url.pathname).then(response => response)); + event.respondWith( + fetch(pattern).catch(() => { + return caches.match(event.request); + }) + ); return; }