From: Ardis Lu Date: Mon, 29 Mar 2021 02:46:57 +0000 (-0700) Subject: Add service worker to cache CMS responses X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=187058899963da8ee5bef62181bc5c81e4e63e86;p=ardislu.dev Add service worker to cache CMS responses My google-api-proxy takes 1-2 seconds to serve content, which is not acceptable. The service worker will automatically cache and serve the last response from the CMS. --- diff --git a/script.js b/script.js index dc9fca0..bc757bf 100644 --- a/script.js +++ b/script.js @@ -1,3 +1,7 @@ +if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/sw.js'); +} + const main = document.getElementsByTagName("main")[0]; const initialColumns = Math.max(1, Math.floor(main.clientWidth / 320) - 1); diff --git a/sw.js b/sw.js new file mode 100644 index 0000000..64122f3 --- /dev/null +++ b/sw.js @@ -0,0 +1,22 @@ +const cacheName = 'v1'; + +self.addEventListener('install', event => { + event.waitUntil((async () => { + const cache = await caches.open(cacheName); + await cache.addAll(['index.html', '404.html', 'style.css', 'script.js', 'favicon.ico', 'github.svg', 'home.svg']); + })()); +}); + +self.addEventListener('fetch', event => { + event.respondWith((async () => { + const fetchResponseP = fetch(event.request); + const fetchResponseCloneP = fetchResponseP.then(r => r.clone()); + + event.waitUntil((async () => { + const cache = await caches.open(cacheName); + await cache.add(event.request.url, await fetchResponseCloneP); + })()); + + return (await caches.match(event.request.url)) || fetchResponseP; + })()); +}); \ No newline at end of file