fix: 修复白屏 — SW networkFirst + initSession try/catch + Error Boundary
1. sw.js: /index.html 导航请求使用 networkFirst 策略替代 cacheFirst, 避免旧 SW 缓存不存在的旧 hash 资源导致 404 白屏 2. App.tsx: initSession 添加 try/catch 异常保护,防止初始化 失败导致整个 React 树崩溃 3. 新建 ErrorBoundary.tsx: React 错误边界组件,捕获渲染异常 显示友好错误页面而非白屏
This commit is contained in:
@@ -38,18 +38,28 @@ self.addEventListener('message', (event) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Fetch: 缓存优先策略(对 API 请求使用网络优先)
|
||||
// Fetch: HTML 导航请求使用 networkFirst,静态资源使用 cacheFirst
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const url = new URL(event.request.url);
|
||||
|
||||
// API 请求:网络优先,失败时返回离线 JSON
|
||||
if (url.pathname.startsWith('/api/')) {
|
||||
event.respondWith(networkFirst(event.request));
|
||||
} else if (url.pathname.startsWith('/ws')) {
|
||||
// WebSocket 连接不缓存
|
||||
// WebSocket 连接不缓存
|
||||
if (url.pathname.startsWith('/ws')) {
|
||||
event.respondWith(fetch(event.request));
|
||||
return;
|
||||
}
|
||||
|
||||
// 导航请求(HTML 页面):网络优先,避免旧缓存引用不存在的 hash 资源 → 白屏
|
||||
const isNavigation =
|
||||
event.request.mode === 'navigate' ||
|
||||
(event.request.headers.get('Accept') || '').includes('text/html');
|
||||
|
||||
if (isNavigation) {
|
||||
event.respondWith(networkFirstForHTML(event.request));
|
||||
} else if (url.pathname.startsWith('/api/')) {
|
||||
// API 请求:网络优先,失败时返回离线 JSON
|
||||
event.respondWith(networkFirst(event.request));
|
||||
} else {
|
||||
// 静态资源:缓存优先
|
||||
// 静态资源(JS/CSS/图片等):缓存优先
|
||||
event.respondWith(cacheFirst(event.request));
|
||||
}
|
||||
});
|
||||
@@ -73,6 +83,27 @@ async function cacheFirst(request) {
|
||||
}
|
||||
}
|
||||
|
||||
async function networkFirstForHTML(request) {
|
||||
try {
|
||||
const response = await fetch(request);
|
||||
if (response.ok) {
|
||||
const cache = await caches.open(CACHE_NAME);
|
||||
cache.put(request, response.clone());
|
||||
}
|
||||
return response;
|
||||
} catch (e) {
|
||||
const cached = await caches.match(request);
|
||||
if (cached) return cached;
|
||||
// 最终 fallback:离线页面
|
||||
const offline = await caches.match('/offline.html');
|
||||
if (offline) return offline;
|
||||
return new Response('离线状态,请检查网络连接', {
|
||||
status: 503,
|
||||
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function networkFirst(request) {
|
||||
try {
|
||||
const response = await fetch(request);
|
||||
|
||||
Reference in New Issue
Block a user