From 4347e2419954ed4f66909d071cbc7e1e3edb11e0 Mon Sep 17 00:00:00 2001 From: Caleb Fultz Date: Wed, 21 Aug 2024 00:02:53 -0400 Subject: [PATCH] Added offline.html and update sw.js --- offline.html | 29 +++++++++++++++++++++ sw.js | 72 +++++++++++++++++++++++++++++++++++++--------------- 2 files changed, 80 insertions(+), 21 deletions(-) create mode 100644 offline.html diff --git a/offline.html b/offline.html new file mode 100644 index 0000000..b31cad6 --- /dev/null +++ b/offline.html @@ -0,0 +1,29 @@ + + + + + + Offline - MTG Card CSV Generator + + + + + + +
+

You're Offline

+

It looks like you are not connected to the internet. Please check your connection and try again.

+

While offline, you can still browse previously loaded content, but some features might not work as expected.

+

+ Go back to the main page +

+
+ + + + diff --git a/sw.js b/sw.js index b159467..403b958 100644 --- a/sw.js +++ b/sw.js @@ -1,24 +1,54 @@ -self.addEventListener('install', (event) => { - event.waitUntil( - caches.open('mtg-csv-generator-v1').then((cache) => { - return cache.addAll([ - '/', - '/index.html', - '/styles.css', - '/app.js', - '/manifest.json', - '/icon.png', - '/cash-money.mp3', - '/randomWords.js' - ]); - }) - ); +// This is the service worker with the combined offline experience (Offline page + Offline copy of pages) + +const CACHE = "pwabuilder-offline-page"; + +importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js'); + +// TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html"; +const offlineFallbackPage = "ToDo-replace-this-name.html"; + +self.addEventListener("message", (event) => { + if (event.data && event.data.type === "SKIP_WAITING") { + self.skipWaiting(); + } }); -self.addEventListener('fetch', (event) => { - event.respondWith( - caches.match(event.request).then((response) => { - return response || fetch(event.request); - }) - ); +self.addEventListener('install', async (event) => { + event.waitUntil( + caches.open(CACHE) + .then((cache) => cache.add(offlineFallbackPage)) + ); }); + +if (workbox.navigationPreload.isSupported()) { + workbox.navigationPreload.enable(); +} + +workbox.routing.registerRoute( + new RegExp('/*'), + new workbox.strategies.StaleWhileRevalidate({ + cacheName: CACHE + }) +); + +self.addEventListener('fetch', (event) => { + if (event.request.mode === 'navigate') { + event.respondWith((async () => { + try { + const preloadResp = await event.preloadResponse; + + if (preloadResp) { + return preloadResp; + } + + const networkResp = await fetch(event.request); + return networkResp; + } catch (error) { + + const cache = await caches.open(CACHE); + const cachedResp = await cache.match(offlineFallbackPage); + return cachedResp; + } + })()); + } +}); \ No newline at end of file