Add (pwa)
This commit is contained in:
67
public/serviceworker.js
Normal file
67
public/serviceworker.js
Normal file
@@ -0,0 +1,67 @@
|
||||
var staticCacheName = "pwa-v" + new Date().getTime();
|
||||
var filesToCache = [
|
||||
// ... (your other initial paths)
|
||||
"/images/icons/icon-72x72.png",
|
||||
"/images/icons/icon-96x96.png",
|
||||
"/images/icons/icon-128x128.png",
|
||||
"/images/icons/icon-144x144.png",
|
||||
"/images/icons/icon-152x152.png",
|
||||
"/images/icons/icon-192x192.png",
|
||||
"/images/icons/icon-384x384.png",
|
||||
"/images/icons/icon-512x512.png",
|
||||
];
|
||||
|
||||
self.addEventListener("install", (event) => {
|
||||
this.skipWaiting();
|
||||
event.waitUntil(
|
||||
fetch("/manifest.json")
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch manifest");
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then((manifest) => {
|
||||
for (let key in manifest) {
|
||||
if (manifest[key].hasOwnProperty("file")) {
|
||||
filesToCache.push("/build/" + manifest[key].file); // Prefixing with "/build/"
|
||||
}
|
||||
}
|
||||
|
||||
return caches.open(staticCacheName).then((cache) => {
|
||||
return cache.addAll(filesToCache);
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error while caching files from manifest:", error);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// Clear cache on activate
|
||||
self.addEventListener("activate", (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys().then((cacheNames) => {
|
||||
return Promise.all(
|
||||
cacheNames
|
||||
.filter((cacheName) => cacheName.startsWith("pwa-"))
|
||||
.filter((cacheName) => cacheName !== staticCacheName)
|
||||
.map((cacheName) => caches.delete(cacheName)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// Serve from Cache
|
||||
self.addEventListener("fetch", (event) => {
|
||||
event.respondWith(
|
||||
caches
|
||||
.match(event.request)
|
||||
.then((response) => {
|
||||
return response || fetch(event.request);
|
||||
})
|
||||
.catch(() => {
|
||||
return caches.match("offline");
|
||||
}),
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user