易于使用且可自定义的 setDefaultHandler();当 service worker 由 Workbox 提供支持时,来自 workbox-routing,除非 generateSW 是构建工具。使用 NetworkFirst 策略用于页面缓存的默认处理程序,因为无法在整个 registerRoute 或 urlPattern 中缓存 html 页面:
({ request }) => request.mode === 'navigate',
我使用 NetworkOnly 策略为第三方来源注册路由,该策略在网站静态资产单独 chached 时运行良好。小型静态 html 页面对于构建 service worker 来说已经足够棘手了,因为 '/'、'/page1/'、'/page2/'、/.../etc。并且它们不会按预期进行缓存。
仅供参考:/ = index.html,/page1/ = /page1/index.htm,/page2/ = /page2/index.htm
Html 页面由默认处理程序管理,因为没有其他路由为它们注册。这是在 service worker 文件中手工编写的自定义 setDefaultHandler:
setDefaultHandler(
new NetworkFirst({
networkTimeoutSeconds: 3,
cacheName: 'runtime',
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
new ExpirationPlugin({
maxEntries: 12,
maxAgeSeconds: 60 * 60 * 24 * 15, // 15 days
matchOptions: {
ignoreVary: true
},
}),
],
}),
);
基于节点的构建过程不能让我们使用/自定义setDefaultHandler。我猜 NetworkOnly 是默认值,没有选择更改。感谢this answer,但是,build.js 包含如下代码片段。无论如何,路由匹配的缓存策略有助于 html 页面缓存:
const {generateSW} = require('workbox-build');
function matchFunction({ url }) {
const pages = ['/', '/page1/', '/page2/', '/.../'];
return pages.includes(url.pathname);
}
generateSW({
// ... other generateSW config options...
runtimeCaching: [
{
urlPattern: matchFunction,
handler: 'NetworkFirst',
options: {
networkTimeoutSeconds: 3,
cacheName: 'runtime',
cacheableResponse: {
statuses: [0, 200]
},
expiration: {
maxEntries: 12,
maxAgeSeconds: 60 * 60 * 24 * 15, // 15 days
matchOptions: {
ignoreVary: true
},
},
precacheFallback: {
fallbackURL: 'offline.html',
},
},
},
// ... other runtimeCaching options...
],
});
自定义处理程序 - 根据@jeff-posnick - 可能是在 build.js 中为运行时缓存设置默认处理程序的一种方式,但我不确定如何需要硬编码。