From cd2533c7882a718f1acb78eec9fa5da2747b48b9 Mon Sep 17 00:00:00 2001 From: Sassan Haradji Date: Sat, 17 Aug 2024 16:20:34 +0400 Subject: [PATCH] feat: add service-worker for caching --- index.html | 21 ++++++++++++--- manifest.json | 2 ++ service-worker.js | 65 +++++++++++++++++++++++++++++++++++++++++++++++ style.css | 2 +- 4 files changed, 85 insertions(+), 5 deletions(-) create mode 100644 service-worker.js diff --git a/index.html b/index.html index 5d14aaf..534411b 100644 --- a/index.html +++ b/index.html @@ -10,7 +10,7 @@ - + @@ -23,13 +23,11 @@ - + - - @@ -50,6 +48,21 @@ + diff --git a/manifest.json b/manifest.json index fc98a49..30dc58b 100644 --- a/manifest.json +++ b/manifest.json @@ -1,5 +1,7 @@ { "name": "qrcodekit", + "manifest_version": 2, + "version": "1.0.0", "short_name": "qrcodekit", "start_url": "/index.html", "display": "standalone", diff --git a/service-worker.js b/service-worker.js new file mode 100644 index 0000000..44ddb0d --- /dev/null +++ b/service-worker.js @@ -0,0 +1,65 @@ +const cacheName = "v1.0.0"; +const cacheAssets = [ + "index.html", + "script.js", + "style.js", + "https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js", + "https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.8/html5-qrcode.min.js", + "https://cdnjs.cloudflare.com/ajax/libs/autosize.js/6.0.1/autosize.min.js", + "https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined", +]; + +// Call Install Event +self.addEventListener("install", (e) => { + console.log("Service Worker: Installed"); + + e.waitUntil( + caches + .open(cacheName) + .then((cache) => { + console.log("Service Worker: Caching Files"); + cache.addAll(cacheAssets); + }) + .then(() => self.skipWaiting()), + ); +}); + +// Call Activate Event +self.addEventListener("activate", (e) => { + console.log("Service Worker: Activated"); + // Remove unwanted caches + e.waitUntil( + caches.keys().then((cacheNames) => { + return Promise.all( + cacheNames.map((cache) => { + if (cache !== cacheName) { + console.log("Service Worker: Clearing Old Cache"); + return caches.delete(cache); + } + }), + ); + }), + ); +}); + +// Call Fetch Event +self.addEventListener("fetch", (e) => { + console.log("Service Worker: Fetching"); + e.respondWith( + fetch(e.request) + .then((res) => { + // Make clone of response + const resClone = res.clone(); + // Open cache + caches.open(cacheName).then((cache) => { + // Add response to cache + cache.put(e.request, resClone); + }); + return res; + }) + .catch(async (err) => { + console.error("Fetch failed; returning cached resource instead.", err); + return await caches.match(e.request); + }), + ); +}); diff --git a/style.css b/style.css index 724cc1a..5d758d4 100644 --- a/style.css +++ b/style.css @@ -1,6 +1,6 @@ body, html { - height: 100%; + height: 100vh; margin: 0; display: flex; justify-content: center;