feat(sw): 升级缓存版本并优化资源缓存策略

- 更新缓存名称从 v1.0.1 到 v1.1.0
- 移除部分图片资源路径配置
- 安装阶段增加 skipWaiting 强制更新
- 优化 fetch 拦截逻辑,区分 HTML、音频、图片及静态资源处理
- 增加对带版本号请求的特殊处理
- 激活阶段主动声明客户端控制权
- 改进缓存匹配忽略查询参数提高命中率
- 增强错误捕获避免中断服务工作线程运行
This commit is contained in:
hehh
2025-11-25 20:05:26 +08:00
parent 5c9e2c4186
commit d19837edc2

View File

@@ -1,5 +1,4 @@
// Service Worker for PWA const CACHE_NAME = 'honesty-home-v1.1.0';
const CACHE_NAME = 'honesty-home-v1.0.1';
const urlsToCache = [ const urlsToCache = [
'./index.html', './index.html',
'./about.html', './about.html',
@@ -7,87 +6,82 @@ const urlsToCache = [
'./css/about.css', './css/about.css',
'./css/artalk.css', './css/artalk.css',
'./js/config.js', './js/config.js',
'./js/main.js',
'./js/about.js', './js/about.js',
'./images/avatar.jpeg', './images/avatar.jpeg',
'./images/favicon.ico', './images/favicon.ico',
'./images/favicon.png', './images/favicon.png',
'./images/logo.png', './images/logo.png',
'./images/INFJ.png', './images/INFJ.png'
'./images/kl.gif',
'./images/bj/1.jpg',
'./images/bj/2.jpg',
'./images/bj/3.jpg',
'./images/bj/4.jpg',
'./images/bj/5.jpg',
'./images/bj/6.jpg',
'./images/bj/7.jpg',
]; ];
// 安装事件 - 缓存资源
self.addEventListener('install', event => { self.addEventListener('install', event => {
event.waitUntil( event.waitUntil(
caches.open(CACHE_NAME) caches.open(CACHE_NAME)
.then(cache => { .then(cache => {
console.log('Opened cache');
return cache.addAll(urlsToCache); return cache.addAll(urlsToCache);
}) })
.catch(() => Promise.resolve())
); );
self.skipWaiting();
}); });
// 获取事件 - 拦截网络请求
self.addEventListener('fetch', event => { self.addEventListener('fetch', event => {
// 对于非GET请求或者不是同源请求直接跳过
if (event.request.method !== 'GET' || !event.request.url.startsWith(self.location.origin)) { if (event.request.method !== 'GET' || !event.request.url.startsWith(self.location.origin)) {
return; return;
} }
const url = new URL(event.request.url);
const isHTML = event.request.mode === 'navigate' || url.pathname.endsWith('.html');
const isVersioned = url.search && /version=/.test(url.search);
const isAudio = url.pathname.endsWith('.mp3') || url.pathname.endsWith('.wav') || url.pathname.endsWith('.ogg');
const isImage = /\.(png|jpg|jpeg|gif|webp|svg)$/i.test(url.pathname);
const isStaticAsset = /\.(css|js|json)$/i.test(url.pathname);
if (isHTML || isVersioned || isAudio) {
event.respondWith( event.respondWith(
caches.match(event.request) fetch(event.request)
.then(response => { .then(resp => {
// 如果在缓存中找到响应,则返回缓存的资源 if (resp && resp.status === 200 && resp.type === 'basic' && !isAudio) {
if (response) { const copy = resp.clone();
return response; caches.open(CACHE_NAME).then(cache => cache.put(event.request, copy)).catch(() => {});
}
return resp;
})
.catch(() => {
return caches.match(event.request, { ignoreSearch: true })
.then(m => m || caches.match(event.request))
})
);
return;
} }
// 克隆请求,因为请求是一个流,只能被消费一次 event.respondWith(
const fetchRequest = event.request.clone(); caches.match(event.request, { ignoreSearch: true })
.then(cached => {
// 如果没有在缓存中找到,则发起网络请求 if (cached) return cached;
return fetch(fetchRequest).then(response => { return fetch(event.request).then(resp => {
// 检查响应是否有效 if (resp && resp.status === 200 && resp.type === 'basic' && (isImage || isStaticAsset)) {
if (!response || response.status !== 200 || response.type !== 'basic') { const copy = resp.clone();
return response; caches.open(CACHE_NAME).then(cache => cache.put(event.request, copy)).catch(() => {});
} }
return resp;
// 克隆响应,因为响应是一个流,只能被消费一次
const responseToCache = response.clone();
// 打开缓存并将响应添加到缓存中
caches.open(CACHE_NAME)
.then(cache => {
cache.put(event.request, responseToCache);
});
return response;
}); });
}) })
); );
}); });
// 激活事件 - 清理旧缓存
self.addEventListener('activate', event => { self.addEventListener('activate', event => {
const cacheWhitelist = [CACHE_NAME]; const cacheWhitelist = [CACHE_NAME];
event.waitUntil( event.waitUntil(
caches.keys().then(cacheNames => { caches.keys().then(cacheNames => {
return Promise.all( return Promise.all(
cacheNames.map(cacheName => { cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) { if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName); return caches.delete(cacheName);
} }
}) })
); );
}) })
); );
self.clients.claim();
}); });