From c2f85823040832d0fc10d313d6af2ae5202fe0fd Mon Sep 17 00:00:00 2001 From: FS-Frost <30810344+FS-Frost@users.noreply.github.com> Date: Thu, 6 Jun 2024 10:16:05 -0400 Subject: [PATCH] PWA. --- public/index.html | 2 +- public/js/worker.js | 51 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 public/js/worker.js diff --git a/public/index.html b/public/index.html index 661fccd..fcc8226 100644 --- a/public/index.html +++ b/public/index.html @@ -33,7 +33,7 @@ if ("serviceWorker" in navigator) { window.addEventListener("load", function () { navigator.serviceWorker - .register("worker.js") + .register("js/worker.js") .then( function (registration) { console.log("Worker registration successful", registration.scope); diff --git a/public/js/worker.js b/public/js/worker.js new file mode 100644 index 0000000..3d6ab80 --- /dev/null +++ b/public/js/worker.js @@ -0,0 +1,51 @@ +// Flag for enabling cache in production +var doCache = false; + +var CACHE_NAME = "pwa-app-cache"; + +// Delete old caches +self.addEventListener("activate", (event) => { + const currentCachelist = [CACHE_NAME]; + event.waitUntil( + caches.keys().then((keyList) => + Promise.all( + keyList.map((key) => { + if (!currentCachelist.includes(key)) { + return caches.delete(key); + } + }) + ) + ) + ); +}); + +// This triggers when user starts the app +self.addEventListener("install", function (event) { + if (doCache) { + event.waitUntil( + caches.open(CACHE_NAME).then(function (cache) { + fetch("asset-manifest.json") + .then((response) => { + response.json(); + }) + .then((assets) => { + // We will cache initial page and the main.js + // We could also cache assets like CSS and images + const urlsToCache = ["/", assets["main.js"]]; + cache.addAll(urlsToCache); + }); + }) + ); + } +}); + +// Here we intercept request and serve up the matching files +self.addEventListener("fetch", function (event) { + if (doCache) { + event.respondWith( + caches.match(event.request).then(function (response) { + return response || fetch(event.request); + }) + ); + } +}); \ No newline at end of file