离线策略
发布于 更新于
Service Worker 可以让 PWA 在断网时仍能加载和使用。应用外壳从缓存读取,数据请求先走网络、 失败后用缓存回退,网络和缓存都未命中的导航则返回已存好的离线页。缓存和网络该怎么用, 需要按请求决定,并没有一个统一的「离线模式」开关。
你需要一个已注册的 Service Worker(没有的话先做入门),并了解 install
与 activate 何时触发,见
Service worker 生命周期:install、activate 与更新。
把各步骤的处理函数加到同一份 sw.js 中;后台同步那一步还需要你自己写一个 replayOutbox() 函数,读取队列并重新发送。
在 install 时预缓存外壳
链接到“在 install 时预缓存外壳”一节在 install 中打开一个带版本号的缓存,用 addAll() 放入每个视图都需要的 HTML、CSS 与 JavaScript,
再加上离线页。下次发布时,修改缓存名中的版本号即可整体替换这组文件。只要有一个文件抓取失败,addAll() 就会
拒绝;传给 waitUntil() 的 Promise 拒绝后,浏览器会放弃本次安装,所以只列出你能控制的文件。
const VERSION = 'v3';const SHELL_CACHE = `shell-${VERSION}`;const DATA_CACHE = `data-${VERSION}`;const SHELL = ['/', '/app.css', '/app.js', '/offline.html'];
self.addEventListener('install', (event) => { event.waitUntil(caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL)));});带哈希文件名的外壳文件可以在缓存存活期间一直缓存优先;不带哈希的 /app.js 只在
worker 重新安装时才更新,sw.js 有改动就会触发;改 VERSION 还会让文件换到新缓存里。
按请求类型路由每个 fetch
链接到“按请求类型路由每个 fetch”一节导航请求先走网络,让用户看到最新 HTML;网络失败后用缓存外壳回退。外壳资源优先读缓存,能立即响应, 等下一个 worker 版本再更新。API 响应也优先走网络,失败后返回最近一次成功的副本,代价是在线时 每次请求都要等一次完整的网络往返。图片和字体采用 stale-while-revalidate,立即返回缓存副本, 同时在后台抓取更新,因此在刷新完成之前,响应可能是旧内容。
self.addEventListener('fetch', (event) => { const { request } = event; if (request.method !== 'GET') return; // POST 之类直接走网络
const url = new URL(request.url); if (request.mode === 'navigate') { event.respondWith(networkFirst(event, SHELL_CACHE, '/offline.html')); } else if (SHELL.includes(url.pathname)) { event.respondWith(caches.match(request).then((hit) => hit || fetch(request))); } else if (url.pathname.startsWith('/api/')) { event.respondWith(networkFirst(event, DATA_CACHE)); } else if (request.destination === 'image' || request.destination === 'font') { event.respondWith(staleWhileRevalidate(event, DATA_CACHE)); }});
async function networkFirst(event, cacheName, fallbackPath) { const { request } = event; const cache = await caches.open(cacheName); try { const fresh = await fetch(request); if (fresh.ok) event.waitUntil(cache.put(request, fresh.clone())); return fresh; } catch { const cached = await cache.match(request); if (cached) return cached; if (fallbackPath) return cache.match(fallbackPath); throw new Error(`offline and ${request.url} is not cached`); }}
async function staleWhileRevalidate(event, cacheName) { const { request } = event; const cache = await caches.open(cacheName); const cached = await cache.match(request); const refresh = fetch(request).then(async (response) => { if (response.ok) await cache.put(request, response.clone()); return response; }); event.waitUntil(refresh.catch(() => {})); // keep the worker alive until the cache write lands return cached || refresh;}cache.put() 会消耗响应体,所以代码先 clone() 再存,返回原始响应。各策略的取舍以及与 Workbox 的对应关系见
选择缓存策略。
在 activate 时删除旧缓存
链接到“在 activate 时删除旧缓存”一节activate 在旧 worker 不再控制任何页面(或新 worker 调用了 skipWaiting())之后运行,这是删除上一版本缓存的安全时机;在此之前打开的页面要重新加载才会受控。缓存在整个源内共享,
所以只删除匹配自身前缀的缓存。保持处理函数简短,激活耗时过长会让 fetch 排队等待。
self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((names) => Promise.all( names .filter((name) => (name.startsWith('shell-') || name.startsWith('data-')) && !name.endsWith(VERSION)) .map((name) => caches.delete(name)), ), ), );});用 Background Sync 排队失败的写入
链接到“用 Background Sync 排队失败的写入”一节networkFirst 对 GET 返回的是旧数据;失败的 POST 需要重试。浏览器提供 ServiceWorkerRegistration.sync
时,把请求体存进 IndexedDB 并注册一个 sync 标签;网络恢复时浏览器触发 sync。该 API 只有 Chromium
实现(版本见 Background Sync 后台同步支持),所以注册抛错时页面也要能工作。
// 页面中,POST 失败之后:async function queueForSync(tag) { const registration = await navigator.serviceWorker.ready; if (!('sync' in registration)) return false; // 改为提示「已保存到本地,稍后重试」 try { await registration.sync.register(tag); return true; } catch { return false; }}
// sw.js 中:self.addEventListener('sync', (event) => { if (event.tag === 'outbox') event.waitUntil(replayOutbox(event.lastChance));});event.lastChance 为 true 表示这次之后浏览器不会再尝试,所以这一轮重放如果失败,就该告诉用户写入没有发出去。
预缓存大文件前先查存储预算
链接到“预缓存大文件前先查存储预算”一节每个缓存都计入源的配额,而逐出可能一次清空全部。navigator.storage.estimate() 返回保守估计的 quota
与当前 usage(单位字节);因为压缩与去重,数字只是近似值。对必须保留的数据请求
navigator.storage.persist(),见存储持久化、配额与逐出。
const { usage, quota } = await navigator.storage.estimate();console.log(`${(usage / 1048576).toFixed(1)} MB used of ${(quota / 1048576).toFixed(0)} MB`);断网重新加载
链接到“断网重新加载”一节先在线加载一次应用让 install 跑完,重新加载一次让 worker 接管页面,打开调用 /api/ 的视图让数据缓存填充,然后在 Chrome DevTools 打开 Network 面板,在 Disable cache
复选框旁的 Network throttling 下拉菜单中选择 Offline(英文界面),再重新加载。外壳从 shell-v3
绘制,/api/ 请求返回最近缓存的副本,导航到未缓存的 URL 时显示 /offline.html。也要从冷启动测试已安装的
应用;已经打开的标签页可能还在用先前加载的资源。
另请参阅
链接到“另请参阅”一节- 选择缓存策略
- Service worker 生命周期:install、activate 与更新
- Service worker 离线兜底
- 存储持久化、配额与逐出
- The Offline Cookbook(web.dev)
- Background Synchronization API(developer.mozilla.org)
- StorageManager: estimate() method(developer.mozilla.org)
← 返回指南总览。