Workbox 服务工作者未在缓存中存储图像和 API 响应
Workbox service worker not storing images and API response in cache
我正在使用 workbox service worker 来缓存图像和 API 响应,方法是为每个创建自定义缓存。虽然我可以看到路由匹配,但我看不到响应存储在缓存中,然后服务人员由于缓存未命中而从网络请求每个资源。
我已经为 service worker 使用了 workbox-webpack-plugin,并在其他文件中编写了自定义路由和缓存策略,然后将其传递给插件配置。
同理,我的 css 和 js 文件存储和服务都很好。
我尝试过使用不同的缓存策略,以及没有 webpack 插件的解决方法,但 none 似乎有效
//Cache JS files
workbox.routing.registerRoute(
new RegExp('.*\.js'),
workbox.strategies.cacheFirst()
);
//Cache API response
workbox.routing.registerRoute(
new RegExp('\/api\/(xyz|abc|def)'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'apiCache',
plugins : [
new workbox.expiration.Plugin({
maxEntries: 100,
maxAgeSeconds: 30 * 60 // 30 Minutes
})
]
})
);
//cache images
workbox.routing.registerRoute(
new RegExp('(png|gif|jpg|jpeg|svg)'),
workbox.strategies.cacheFirst({
cacheName: 'images',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
})
]
})
);
这是 webpack 配置:
new workboxPlugin.InjectManifest({
swSrc: 'customWorkbox.js',
swDest: 'sw.js'
})
根据 workbox docs 外部 api 的正则表达式需要从头开始匹配:
Instead of matching against any part of the URL, the regular expression must match from the beginning of the URL in order to trigger a route when there's a cross-origin request.
我正在使用 workbox service worker 来缓存图像和 API 响应,方法是为每个创建自定义缓存。虽然我可以看到路由匹配,但我看不到响应存储在缓存中,然后服务人员由于缓存未命中而从网络请求每个资源。
我已经为 service worker 使用了 workbox-webpack-plugin,并在其他文件中编写了自定义路由和缓存策略,然后将其传递给插件配置。
同理,我的 css 和 js 文件存储和服务都很好。
我尝试过使用不同的缓存策略,以及没有 webpack 插件的解决方法,但 none 似乎有效
//Cache JS files
workbox.routing.registerRoute(
new RegExp('.*\.js'),
workbox.strategies.cacheFirst()
);
//Cache API response
workbox.routing.registerRoute(
new RegExp('\/api\/(xyz|abc|def)'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'apiCache',
plugins : [
new workbox.expiration.Plugin({
maxEntries: 100,
maxAgeSeconds: 30 * 60 // 30 Minutes
})
]
})
);
//cache images
workbox.routing.registerRoute(
new RegExp('(png|gif|jpg|jpeg|svg)'),
workbox.strategies.cacheFirst({
cacheName: 'images',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
})
]
})
);
这是 webpack 配置:
new workboxPlugin.InjectManifest({
swSrc: 'customWorkbox.js',
swDest: 'sw.js'
})
根据 workbox docs 外部 api 的正则表达式需要从头开始匹配:
Instead of matching against any part of the URL, the regular expression must match from the beginning of the URL in order to trigger a route when there's a cross-origin request.