我们来看看灯塔的源代码 https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/audits/webapp-install-banner.js
static assessOfflineStartUrl(artifacts, result) {
const hasOfflineStartUrl = artifacts.StartUrl.statusCode === 200;
if (!hasOfflineStartUrl) {
result.failures.push('Manifest start_url is not cached by a service worker');
}
}
我们可以注意到,它是不检查缓存,而是检查入口点的响应。原因一定是您的服务工作人员在获取时没有发送正确的响应。
You'll know that it's working, if in DevTools, in your first request, there'll be (from ServiceWorker) in size column:
您提供的代码有两个问题:
第一个是你搞砸了服务人员代码与服务人员登记代码。 Service Worker 注册代码应该是在您的网页上执行的代码。
该代码应包含在您的页面上:
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/worker.js').then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
您粘贴的其余内容应该是您的worker.js 代码。但是,服务工作人员已安装,因为您的缓存中有文件,所以我怀疑您只是错误地粘贴了该文件。
第二个(真正的)问题是服务工作人员没有返回此缓存文件。正如我之前证明的那样,来自灯塔的错误意味着服务人员没有返回start_url
条目文件。
实现这一点的最基本的代码是:
self.addEventListener('fetch', function(event) {
event.respondWith(caches.match(event.request));
});
Service Worker 是事件驱动的,因此当您的页面想要获取某些资源时,Service Worker 会做出反应,并从缓存中提供资源。在现实世界中,你真的不想那样使用它,因为你需要某种后备。我强烈推荐阅读部分从这里的缓存中提供文件 https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker
Edit: 我创建了拉取请求 https://github.com/GoogleChrome/lighthouse/pull/2775在 Lighthouse 源代码中澄清该错误消息