93 lines
2.5 KiB
JavaScript
93 lines
2.5 KiB
JavaScript
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
|
|
const CACHE_NAME = "pwa-cache-v4";
|
|
|
|
// نصب 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);
|
|
|
|
// navigation: همیشه از شبکه — HTML کش نشود تا title/meta همیشه تازه باشد
|
|
if (event.request.mode === "navigate") {
|
|
event.respondWith(fetch(event.request));
|
|
return;
|
|
}
|
|
|
|
// آیکونها: 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;
|
|
})
|
|
);
|
|
}
|
|
});
|