diff --git a/public/serviceworker.js b/public/serviceworker.js new file mode 100644 index 0000000..9bd153e --- /dev/null +++ b/public/serviceworker.js @@ -0,0 +1,41 @@ +const CACHE_NAME = "version-1"; +const urlsToCache = ["index.html", "offline.html"]; + +// Install SW +self.addEventListener("install", (event) => { + event.waitUntil( + caches.open(CACHE_NAME).then((cache) => { + console.log("Opened cache"); + return cache.addAll(urlsToCache); + }) + ); +}); + +// Listen for Request +self.addEventListener("fetch", (event) => { + event.respondWith( + caches.match(event.request).then(() => { + return fetch(event.request).catch(() => { + caches.match("offline.html"); + }); + }) + ); +}); + +// Activate the SW +self.addEventListener("activate", (event) => { + const cacheWhitelist = []; + cacheWhitelist.push(CACHE_NAME); + + event.waitUntil( + caches.keys().then((cacheNames) => + Promise.all( + cacheNames.map((cacheName) => { + if (!cacheWhitelist.includes(cacheName)) { + return caches.delete(cacheName); + } + }) + ) + ) + ); +});