diff --git a/index.html b/index.html index 74687d3..a3005f1 100644 --- a/index.html +++ b/index.html @@ -141,6 +141,11 @@

+ diff --git a/js/pwabuilder-sw.js b/js/pwabuilder-sw.js new file mode 100644 index 0000000..403b958 --- /dev/null +++ b/js/pwabuilder-sw.js @@ -0,0 +1,54 @@ +// 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('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