Skip to content

Commit 98ecf5b

Browse files
fix(pwa): 优化服务工作者的激活和缓存策略,确保用户始终获取最新内容
Signed-off-by: wangsimiao1 <wangsimiao1@xiaomi.com>
1 parent 1aa6b2f commit 98ecf5b

4 files changed

Lines changed: 29 additions & 6 deletions

File tree

_javascript/pwa/app.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,17 @@ if ('serviceWorker' in navigator) {
1313
const popupWindow = Toast.getOrCreateInstance(notification);
1414

1515
navigator.serviceWorker.register(swUrl).then((registration) => {
16-
// Restore the update window that was last manually closed by the user
16+
// If a new service worker is already waiting, activate it immediately
1717
if (registration.waiting) {
18-
popupWindow.show();
18+
registration.waiting.postMessage('SKIP_WAITING');
1919
}
2020

2121
registration.addEventListener('updatefound', () => {
2222
registration.installing.addEventListener('statechange', () => {
2323
if (registration.waiting) {
2424
if (navigator.serviceWorker.controller) {
25-
popupWindow.show();
25+
// Automatically activate the new service worker
26+
registration.waiting.postMessage('SKIP_WAITING');
2627
}
2728
}
2829
});

_javascript/pwa/sw.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,29 @@ self.addEventListener('fetch', (event) => {
6666
return;
6767
}
6868

69+
// Use network-first strategy for navigation requests (HTML pages)
70+
// so users always see the latest content
71+
if (event.request.mode === 'navigate') {
72+
event.respondWith(
73+
fetch(event.request)
74+
.then((response) => {
75+
if (purge || event.request.method !== 'GET' || !verifyUrl(event.request.url)) {
76+
return response;
77+
}
78+
let responseToCache = response.clone();
79+
caches.open(swconf.cacheName).then((cache) => {
80+
cache.put(event.request, responseToCache);
81+
});
82+
return response;
83+
})
84+
.catch(() => {
85+
return caches.match(event.request);
86+
})
87+
);
88+
return;
89+
}
90+
91+
// Cache-first strategy for static assets (CSS, JS, images, etc.)
6992
event.respondWith(
7093
caches.match(event.request).then((response) => {
7194
if (response) {
@@ -79,7 +102,6 @@ self.addEventListener('fetch', (event) => {
79102
return response;
80103
}
81104

82-
// See: <https://developers.google.com/web/fundamentals/primers/service-workers#cache_and_return_requests>
83105
let responseToCache = response.clone();
84106

85107
caches.open(swconf.cacheName).then((cache) => {

0 commit comments

Comments
 (0)