Files
dms/client/public/sw.js
T
2026-08-10 22:56:38 +08:00

51 lines
1.4 KiB
JavaScript

/* 简易 Service Worker:缓存静态资源,支持离线访问与 PWA 安装 */
const CACHE_NAME = 'dms-cache-v1';
const STATIC_ASSETS = [
'/',
'/index.html',
'/manifest.webmanifest',
'/assets/logo-icon.png',
'/assets/logo-white.png',
'/assets/logo-dark.png'
];
// 安装阶段:预缓存静态资源
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(STATIC_ASSETS))
);
self.skipWaiting();
});
// 激活阶段:清理旧缓存
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
)
);
self.clients.claim();
});
// 请求阶段:API 走网络,静态资源优先缓存
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
// API 请求不缓存
if (url.pathname.startsWith('/api')) return;
event.respondWith(
caches.match(event.request).then((cached) => {
if (cached) return cached;
return fetch(event.request).then((response) => {
// 只缓存同源 GET 静态资源
if (event.request.method === 'GET' && url.origin === self.location.origin) {
const clone = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
}
return response;
});
}).catch(() => caches.match('/index.html'))
);
});