Add PWA support with service worker, manifest, and offline page

This commit is contained in:
dhanabalan
2025-11-04 09:44:37 +05:30
parent f47f5182a2
commit aed8c36089
5 changed files with 223 additions and 0 deletions

47
public/sw.js Normal file
View File

@@ -0,0 +1,47 @@
"use strict";
const CACHE_NAME = "offline-cache-v1";
const OFFLINE_URL = '/offline.html';
const filesToCache = [
OFFLINE_URL
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(filesToCache))
);
});
self.addEventListener("fetch", (event) => {
if (event.request.mode === 'navigate') {
event.respondWith(
fetch(event.request)
.catch(() => {
return caches.match(OFFLINE_URL);
})
);
} else {
event.respondWith(
caches.match(event.request)
.then((response) => {
return response || fetch(event.request);
})
);
}
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
})
);
});