Workbox CacheFirst 始终从网络获取(从缓存完成后)
我有一个 Web 应用程序想要缓存最近引用的图像以支持离线使用。这些图像预计不会发生变化,因此我配置了基于 Workbox 的服务工作人员使用 CacheFirst 策略对于来自图像服务器的所有请求:
//service-worker.js
self.skipWaiting();
clientsClaim();
cleanupOutdatedCaches();
registerRoute(
({ request }) => request.url.startsWith('https://example.com'),
new CacheFirst({
cacheName: 'images',
plugins: [
new CacheableResponsePlugin({ statuses: [200] }),
new ExpirationPlugin({
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
maxEntries: 100,
}),
],
})
);
当我的应用程序运行时,我可以在 Chrome 开发人员工具“网络”选项卡中看到服务工作线程在初始加载后成功提供这些图像:
到目前为止一切顺利。但是,“网络”选项卡中还有另一个请求,表明 Service Worker 本身正在从网络获取图像(此处由浏览器的磁盘缓存满足):
我对 CacheFirst 的理解是如果缓存满足请求,Service Worker 根本不应该发出网络请求。是什么导致了这种行为?
I have a web application that wants to cache recently-referenced images to support offline use. The images are not expected to ever change, so I have configured my Workbox-based service worker to use the CacheFirst strategy for all requests from the image server:
//service-worker.js
self.skipWaiting();
clientsClaim();
cleanupOutdatedCaches();
registerRoute(
({ request }) => request.url.startsWith('https://example.com'),
new CacheFirst({
cacheName: 'images',
plugins: [
new CacheableResponsePlugin({ statuses: [200] }),
new ExpirationPlugin({
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
maxEntries: 100,
}),
],
})
);
When my application runs, I can see in Chrome developer tools Network tab that the service worker is successfully serving these images after the initial load:
So far so good. But then, there is another request in the Network tab that indicates that the service worker itself is fetching the image from the network (here, satisified by the browser's disk cache):
My understanding of CacheFirst is that the service worker should not make a network request at all if the cache satisfies the request. What is causing this behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在调试时,我错过了 Chrome 开发者工具中 Workbox 的这条消息:
这让我找到了有关不透明响应的信息,以及一些描述第三方请求的有用信息,这使我能够使用 crossorigin 属性:
回想起来,原始图像的另一个线索根本没有被缓存(即使他们得到了服务工作者的满足)是Chrome开发者工具中的缓存存储资源管理器仅显示工作箱预缓存(而不是我的保存这些缓存图像的“图像”缓存):
While debugging, I had missed this message from Workbox in the Chrome developer tools:
This led me to find information about opaque responses, and some helpful information describing third-party requests, which allowed me to fix this in my environment using the crossorigin attribute in
<img>
tags:In retrospect, another clue that the original images weren't being cached at all (even though they were being satisified by the service worker) was that the Cache Storage explorer in Chrome developer tools showed only the workbox precache (and not my "images" cache that would hold these cached images):