]> git.ardis.lu - ardislu.dev/commitdiff
Add service worker to cache CMS responses
authorArdis Lu <ardisglu@gmail.com>
Mon, 29 Mar 2021 02:46:57 +0000 (19:46 -0700)
committerArdis Lu <ardisglu@gmail.com>
Mon, 29 Mar 2021 02:46:57 +0000 (19:46 -0700)
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.

script.js
sw.js [new file with mode: 0644]

index dc9fca023704fd5ab5e5e24626af76127bc4f825..bc757bfa3160c8d3573b9c81bb07c6c19adf85c4 100644 (file)
--- 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 (file)
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
This page took 0.039579 seconds and 4 git commands to generate.