我刚刚使用appcache构建了一个离线的第一个应用程序,并希望将其转换为使用service-worker(我的客户端都使用最新的chrome,因此我没有任何浏览器兼容性问题)。
我正在使用sw-precache生成一个缓存我的本地资产的服务工作者(特别是我的html / css / fonts以及一些js),看起来当service-worker安装时,它确实成功添加所有缓存存储的资产都成功启动(安装并激活fire并成功完成。我在安装事件结束时有self.skipWaiting()来启动service-worker(它也成功运行) ))。
问题是“fetch”事件似乎没有发生过。因此,如果我离线或打开浏览器(虽然已经离线)并导航到该网站,我会让Chrome离线恐龙。当我查看网络选项卡时,看起来浏览器正试图命中服务器以检索页面。我不确定我做错了什么,我没有触及sw-precache实用程序生成的fetch方法......所以我不确定我缺少什么。任何帮助将不胜感激。我的获取事件如下:
self.addEventListener('fetch', function(event) {
if (event.request.method === 'GET') {
var urlWithoutIgnoredParameters = stripIgnoredUrlParameters(event.request.url,
IgnoreUrlParametersMatching);
var cacheName = AbsoluteUrlToCacheName[urlWithoutIgnoredParameters];
var directoryIndex = 'index.html';
if (!cacheName && directoryIndex) {
urlWithoutIgnoredParameters = addDirectoryIndex(urlWithoutIgnoredParameters, directoryIndex);
cacheName = AbsoluteUrlToCacheName[urlWithoutIgnoredParameters];
}
var navigateFallback = '';
// Ideally, this would check for event.request.mode === 'navigate', but that is not widely
// supported yet:
// https://code.google.com/p/chromium/issues/detail?id=540967
// https://bugzilla.mozilla.org/show_bug.cgi?id=1209081
if (!cacheName && navigateFallback && event.request.headers.has('accept') &&
event.request.headers.get('accept').includes('text/html') &&
/* eslint-disable quotes, comma-spacing */
isPathWhitelisted([], event.request.url)) {
/* eslint-enable quotes, comma-spacing */
var navigateFallbackUrl = new URL(navigateFallback, self.location);
cacheName = AbsoluteUrlToCacheName[navigateFallbackUrl.toString()];
}
if (cacheName) {
event.respondWith(
// Rely on the fact that each cache we manage should only have one entry, and return that.
caches.open(cacheName).then(function(cache) {
return cache.keys().then(function(keys) {
return cache.match(keys[0]).then(function(response) {
if (response) {
return response;
}
// If for some reason the response was deleted from the cache,
// raise and exception and fall back to the fetch() triggered in the catch().
throw Error('The cache ' + cacheName + ' is empty.');
});
});
}).catch(function(e) {
console.warn('Couldn\'t serve response for "%s" from cache: %O', event.request.url, e);
return fetch(event.request);
})
);
}
} });