Skip to content

Commit 26feecf

Browse files
committed
fix: refresh cache strategy
1 parent 2adcdd9 commit 26feecf

2 files changed

Lines changed: 31 additions & 10 deletions

File tree

index.html

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -912,7 +912,10 @@ <h3>设计理念</h3>
912912

913913
if ('serviceWorker' in navigator) {
914914
window.addEventListener('load', () => {
915-
navigator.serviceWorker.register('/service-worker.js').catch(() => {});
915+
navigator.serviceWorker
916+
.register('/service-worker.js', { updateViaCache: 'none' })
917+
.then((registration) => registration.update())
918+
.catch(() => {});
916919
});
917920
}
918921
</script>

service-worker.js

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const CACHE_NAME = 'justhtmls-v1';
1+
const CACHE_NAME = 'justhtmls-v1.1';
22
const PRECACHE_URLS = [
33
'/',
44
'/index.html',
@@ -7,6 +7,10 @@ const PRECACHE_URLS = [
77
'/assets/vendor/fontawesome/css/all.min.css',
88
];
99

10+
const NETWORK_FIRST_PATHS = [
11+
'/index.json',
12+
];
13+
1014
const CACHE_FIRST_PATHS = [
1115
'/assets/vendor/',
1216
'/tools/',
@@ -52,18 +56,32 @@ self.addEventListener('fetch', (event) => {
5256
}
5357

5458
const { pathname } = new URL(request.url);
55-
if (CACHE_FIRST_PATHS.some((path) => pathname.startsWith(path))) {
59+
if (NETWORK_FIRST_PATHS.includes(pathname)) {
5660
event.respondWith(
57-
caches.match(request).then((cached) => {
58-
if (cached) {
59-
return cached;
60-
}
61-
return fetch(request).then((response) => {
61+
fetch(request)
62+
.then((response) => {
6263
const copy = response.clone();
6364
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy));
6465
return response;
65-
});
66-
})
66+
})
67+
.catch(() => caches.match(request))
68+
);
69+
return;
70+
}
71+
72+
if (CACHE_FIRST_PATHS.some((path) => pathname.startsWith(path))) {
73+
event.respondWith(
74+
caches.open(CACHE_NAME).then((cache) =>
75+
cache.match(request).then((cached) => {
76+
const networkFetch = fetch(request)
77+
.then((response) => {
78+
cache.put(request, response.clone());
79+
return response;
80+
})
81+
.catch(() => cached);
82+
return cached || networkFetch;
83+
})
84+
)
6785
);
6886
return;
6987
}

0 commit comments

Comments
 (0)