64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||
|
||
// نصب Service Worker
|
||
self.addEventListener("install", (event) => {
|
||
console.log("Service Worker installing...");
|
||
|
||
event.waitUntil(
|
||
caches.open("pwa-cache-v1").then((cache) => {
|
||
return cache.addAll([
|
||
"/",
|
||
"/manifest.json",
|
||
"/images/icons/256x256.png",
|
||
"/images/icons/512x512.png"
|
||
]);
|
||
})
|
||
);
|
||
});
|
||
|
||
// فعالسازی Service Worker
|
||
self.addEventListener("activate", (event) => {
|
||
console.log("Service Worker activated.");
|
||
// پاک کردن cacheهای قدیمی
|
||
event.waitUntil(
|
||
caches.keys().then((keys) =>
|
||
Promise.all(
|
||
keys
|
||
.filter((key) => key !== "pwa-cache-v1")
|
||
.map((key) => caches.delete(key))
|
||
)
|
||
)
|
||
);
|
||
});
|
||
|
||
// هندل درخواستها
|
||
self.addEventListener("fetch", (event) => {
|
||
const url = new URL(event.request.url);
|
||
|
||
// فقط برای فایلهای استاتیک از cache استفاده کن
|
||
if (
|
||
url.pathname.startsWith("/images/") ||
|
||
url.pathname.endsWith(".png") ||
|
||
url.pathname.endsWith(".jpg") ||
|
||
url.pathname.endsWith(".jpeg") ||
|
||
url.pathname.endsWith(".gif") ||
|
||
url.pathname.endsWith(".webp") ||
|
||
url.pathname.endsWith("manifest.json")
|
||
) {
|
||
event.respondWith(
|
||
caches.match(event.request).then((response) => {
|
||
return (
|
||
response ||
|
||
fetch(event.request).then((res) => {
|
||
// فایل جدید رو هم ذخیره کن
|
||
return caches.open("pwa-cache-v1").then((cache) => {
|
||
cache.put(event.request, res.clone());
|
||
return res;
|
||
});
|
||
})
|
||
);
|
||
})
|
||
);
|
||
}
|
||
});
|