- In public/index.html add following:
<script>
if ("serviceWorker" in Navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker
.register("/service-worker.js")
.then((reg) => {
console.log("worker registered");
})
.catch((err) => {
console.log("Service worker error", err);
});
});
}
</script>
- Create new file in public folder called serviceWorker.js
const CACHE_NAME = "version-1";
const urlToCache = ["index.html", "offline.html"];
this.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log("Opened Cache");
return cache.addAll(urlToCache);
})
);
});
this.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((res) => {
return fetch(event.request).catch(() => caches.match("offline.html"));
})
);
});
this.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);
}
})
)
)
);
});
Download Lighthouse extension
Check if lighthouse report is affirmative to create a PWA
Update your manifest.json file as per requirement
Reference
ย