From e30593f84947ae2e5188cee071746634661fe0d4 Mon Sep 17 00:00:00 2001 From: Victor Westerlund Date: Sun, 6 Dec 2020 05:38:36 +0100 Subject: [PATCH] dev12060537 - ServiceWorker basic boilerplate Added a boilerplate for a offline-first sw. Need to add support for non-standard same-origin assets --- public/assets/js/script.js | 3 ++ public/sw.js | 65 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/public/assets/js/script.js b/public/assets/js/script.js index e69de29..91142fd 100644 --- a/public/assets/js/script.js +++ b/public/assets/js/script.js @@ -0,0 +1,3 @@ +if(navigator.serviceWorker) { + navigator.serviceWorker.register("sw.js"); +} \ No newline at end of file diff --git a/public/sw.js b/public/sw.js index e69de29..e909c92 100644 --- a/public/sw.js +++ b/public/sw.js @@ -0,0 +1,65 @@ +const activeCaches = [ + "content-v1" +]; + +const root = "/victorwesterlund.com/public/"; + +self.addEventListener("install", event => { + event.waitUntil( + caches.open("content-v1").then(cache => cache.addAll([ + root, + root + "assets/css/style.css", + root + "assets/img/favicon.png", + root + "assets/js/script.js", + root + "assets/fonts/RobotoMono-Bold.woff2", + root + "assets/fonts/RobotoMono-Regular.woff2" + ])) + ) +}); + +self.addEventListener("activate", event => { + event.waitUntil( + // Delete inactive caches + caches.keys().then(cacheNames => { + return Promise.all( + cacheNames.map(cacheName => { + if(!activeCaches.includes(cacheName)) { + return caches.delete(cacheName); + } + }) + ) + }) + ) +}); + +/* ---- */ + +function handleRequest(event) { + const networkFetch = fetch(event.request); + + event.waitUntil( + networkFetch.then(response => { + const responseClone = response.clone(); + caches.open("downloaded").then(cache => cache.put(event.request, responseClone)); + }) + ); + + return caches.match(event.request).then(response => response || networkFetch); +} + +self.addEventListener("fetch", event => { + const url = new URL(event.request.url); + + console.log(url); + if(url.origin != location.origin) { + event.respondWith(fetch(url.href)); + } + + // if(url.origin == location.origin && url.pathname == root) { + // event.respondWith(caches.match("index.html")); + // return; + // } + + event.respondWith(caches.match(url.pathname) || handleRequest(event)); +}); +// Victor Westerlund