对于服务人员来说,这是一个全新的事物,JS承诺,因此可以提供任何帮助。
失败的网页:
Chrome开发工具中显示的错误:
The FetchEvent for "http://localhost:3005/" resulted in a network error
response: the promise was rejected.
Promise.catch (async)
(anonymous) @ sw.js:29
sw.js:1 Uncaught (in promise) TypeError: Failed to fetch
注册服务人员的标记(似乎可以正常工作)
if('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.then(function() { console.log("Service Worker Registered"); });
}
sw.js
脚本文件中的安装代码
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open('airhorner').then(function(cache) {
/* Particular urls which all install with code 200s */
})
);
});
最后是event.respondWith()
函数似乎有问题的提取代码
self.addEventListener('fetch', event => {
// Let the browser do its default thing
// for non-GET requests.
if (event.request.method != 'GET') return;
// Prevent the default, and handle the request ourselves.
event.respondWith(async function() {
// Try to get the response from a cache.
const cache = await caches.open('dynamic-v1');
const cachedResponse = await cache.match(event.request);
if (cachedResponse) {
// If we found a match in the cache, return it, but also
// update the entry in the cache in the background.
event.waitUntil(cache.add(event.request));
return cachedResponse;
}
// If we didn't find a match in the cache, use the network.
return fetch(event.request);
}());
});