Files
modstagram-next/public/service-worker.js
payacom 2863cdf490 updata
2026-07-10 18:17:11 +03:30

80 lines
2.2 KiB
JavaScript

/* eslint-disable @typescript-eslint/no-unused-vars */
const CACHE_NAME = "pwa-cache-v2";
// نصب Service Worker
self.addEventListener("install", (event) => {
console.log("Service Worker installing...");
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll([
"/",
"/manifest.json",
"/images/icons/256x256.png",
"/images/icons/512x512.png",
]);
})
);
self.skipWaiting();
});
// فعال‌سازی Service Worker
self.addEventListener("activate", (event) => {
console.log("Service Worker activated.");
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key))
)
).then(() => self.clients.claim())
);
});
// هندل درخواست‌ها
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
// آیکون‌ها: network-first تا تغییرات فوری اعمال شوند
if (url.pathname.startsWith("/images/icons/")) {
event.respondWith(
fetch(event.request)
.then((res) => {
if (res.ok) {
const clone = res.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
}
return res;
})
.catch(() => caches.match(event.request))
);
return;
}
// سایر فایل‌های استاتیک: stale-while-revalidate
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((cached) => {
const networkFetch = fetch(event.request).then((res) => {
if (res.ok) {
const clone = res.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
}
return res;
});
return cached || networkFetch;
})
);
}
});