我非常了解如何创建网页,但是最近我遇到了一些麻烦。我想为我的网站创建服务工作者。奇怪的是,我实际上对它的任何功能都没有特定的用途。我想创建它,以便:
我的代码已经完成了第二个目标。但是,我没有通过两次审核,我对它们的含义以及如何通过均不知所措。我的代码如下:
index.html
<!DOCTYPE html>
<html>
<head>
<!-- Head code -->
</head>
<body>
<!-- Body code -->
<script src="/lib/main.js"></script>
</body>
</html>
main.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./service-worker.js', { scope: './' })
.then(function(registration) {
console.log("Service Worker Registered");
})
.catch(function(err) {
console.log("Service Worker Failed to Register", err);
})
}
service-worker.js
var cacheName = 'v1';
var cacheFiles = [];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Installed');
e.waitUntil(caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching cacheFiles');
return cache.addAll(cacheFiles);
}));
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activated');
e.waitUntil(caches.keys().then(function(cacheNames) {
return Promise.all(cacheNames.map(function(thisCacheName) {
if (thisCacheName !== cacheName) {
console.log('[ServiceWorker] Removing Cached Files from Cache - ', thisCacheName);
return caches.delete(thisCacheName);
}
}));
})
}); self.addEventListener('fetch', function(e) {
console.log('[ServiceWorker] Fetch', e.request.url);
e.respondWith(caches.match(e.request).then(function(response) {
if (response) {
console.log("[ServiceWorker] Found in Cache", e.request.url, response);
return response;
}
var requestClone = e.request.clone();
return fetch(requestClone).then(function(response) {
if (!response) {
console.log("[ServiceWorker] No response from fetch ")
return response;
}
var responseClone = response.clone();
caches.open(cacheName).then(function(cache) {
cache.put(e.request, responseClone);
console.log('[ServiceWorker] New Data Cached', e.request.url);
return response;
});
}).catch(function(err) {
console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
});
}));
});
现在,此代码在大多数情况下可以正常工作。但是在Chrome浏览器的Lighthouse中,我看到了这个
我不知道这些失败的审计意味着什么,我所做的研究也无济于事。