Chrome v72似乎忽略了Cache-Control标头并缓存了service-worker.js为了测试,我设置了所有要使用的资源:
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
res.set('Max-Age', '0');
当导航到localhost:4000 / dist / service-worker.js时,我能够验证这是否设置正确:
HTTP/1.1 200 OK
X-Powered-By: Express
Cache-Control: no-store, no-cache, must-revalidate, private
Max-Age: 0
Access-Control-Allow-Origin: *
Accept-Ranges: bytes
Last-Modified: Thu, 14 Feb 2019 23:17:55 GMT
ETag: W/"3c1-168ee4d6297"
Content-Type: application/javascript; charset=UTF-8
Content-Length: 961
Vary: Accept-Encoding
Date: Thu, 14 Feb 2019 23:27:24 GMT
Connection: keep-alive
即便如此,从Chrome 68开始,默认情况下它“应该”绕过HTTP缓存:https://developers.google.com/web/updates/2018/06/fresher-sw
显然不是。
我在“应用程序”选项卡中检查了重新加载的更新。我关闭了Chrome并重新打开,它仍在使用缓存中的旧service-worker.js。
我的工作箱配置如下:
new GenerateSW({
include: [/\.css$/, /\.js$/],
clientsClaim: true,
skipWaiting: true
}),
我也能够验证,Chrome正在缓存service-worker.js,因为如果我:
倒数第二次测试:
最后的测试:
navigator.serviceWorker.register(`/dist/service-worker.js?hack=${Math.random()}`)
当然,现在它会获取所有新的service-worker.js更新。
这是Chrome Bug吗?我没有正确配置? Chrome Canary也会出现同样的行为。
或者,我可以执行以下操作来绕过缓存:
navigator.serviceWorker
.register(`/dist/sw.js`)
.then(registration => {
registration.update();
})
但这似乎是一个黑客......
由于文件位于/dist/service-worker.js而不是根目录,因此它最终成为一个范围问题。
要修复范围问题,我需要将以下标头添加到服务工作者响应中:
res.set('Service-Worker-Allowed', '/');
然后在注册时:
navigator.serviceWorker.register(`/dist/sw.js`, { scope: '/' });
非常感谢这篇文章:https://developers.google.com/web/tools/workbox/guides/troubleshoot-and-debug