Skip to content

Commit 3f02376

Browse files
committed
feat: code by Trae
1 parent 7c2668d commit 3f02376

1 file changed

Lines changed: 33 additions & 11 deletions

File tree

epub_browser/assets/sw.js

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const CACHE_NAME = 'epub-browser-v1';
1+
const CACHE_NAME = 'epub-browser-v3';
22
const STATIC_ASSETS = [
33
'/',
44
'/index.html',
@@ -80,6 +80,33 @@ self.addEventListener('fetch', (event) => {
8080
return;
8181
}
8282

83+
// 对于导航请求(页面跳转),使用网络优先策略
84+
if (event.request.mode === 'navigate') {
85+
event.respondWith(
86+
fetch(event.request, { redirect: 'follow' })
87+
.then((response) => {
88+
// 缓存响应(包括重定向后的最终响应)
89+
if (response) {
90+
const responseToCache = response.clone();
91+
caches.open(CACHE_NAME)
92+
.then((cache) => {
93+
cache.put(event.request, responseToCache);
94+
});
95+
}
96+
return response;
97+
})
98+
.catch(() => {
99+
// 网络失败时,返回缓存
100+
return caches.match(event.request)
101+
.then((cachedResponse) => {
102+
return cachedResponse || caches.match('/index.html');
103+
});
104+
})
105+
);
106+
return;
107+
}
108+
109+
// 其他请求使用缓存优先策略
83110
event.respondWith(
84111
caches.match(event.request)
85112
.then((cachedResponse) => {
@@ -93,15 +120,10 @@ self.addEventListener('fetch', (event) => {
93120
}
94121

95122
// 否则从网络获取
96-
return fetch(event.request)
123+
return fetch(event.request, { redirect: 'follow' })
97124
.then((response) => {
98-
// 检查是否是有效的响应
99-
if (!response || response.status !== 200 || response.type !== 'basic') {
100-
return response;
101-
}
102-
103-
// 如果应该缓存,则缓存响应
104-
if (shouldCache(event.request.url)) {
125+
// 缓存响应
126+
if (response && shouldCache(event.request.url)) {
105127
const responseToCache = response.clone();
106128
caches.open(CACHE_NAME)
107129
.then((cache) => {
@@ -123,9 +145,9 @@ self.addEventListener('fetch', (event) => {
123145

124146
// 后台更新缓存
125147
function fetchAndCache(request) {
126-
fetch(request)
148+
fetch(request, { redirect: 'follow' })
127149
.then((response) => {
128-
if (response && response.status === 200 && response.type === 'basic') {
150+
if (response) {
129151
caches.open(CACHE_NAME)
130152
.then((cache) => {
131153
cache.put(request, response);

0 commit comments

Comments
 (0)