From 0744081bb49d3558573a00d459078b72e9168263 Mon Sep 17 00:00:00 2001 From: Pranav Yadav Date: Sat, 23 Oct 2021 16:04:46 +0530 Subject: [PATCH] =?UTF-8?q?Added=20serviceworker.js=20=F0=9F=91=A8?= =?UTF-8?q?=E2=80=8D=F0=9F=94=A7=E2=9A=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 🛠 - 🔧 - 🗜 --- public/serviceworker.js | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 public/serviceworker.js 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); + } + }) + ) + ) + ); +});