我有一个简单的服务工作者,它将两个资源(index.html,app.js)添加到缓存中(在安装时),删除旧缓存(在激活时)并从缓存中提供资源(如果存在),否则从网络中提供(在取) . 要使新服务工作者注册并删除旧缓存,我会使用每个新资源版本增加CACHE_NAME中的版本号:
var CACHE_NAME = 'test-cache-v4';
var urlsToCache = ['./','./app.js'];
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function (cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
return self.skipWaiting();
});
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== CACHE_NAME) {
return caches.delete(key);
}
}));
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open(CACHE_NAME).then(function(cache){
return cache.match(event.request)
.then(function(response) {
if (response) {
console.log('SERVED FROM CACHE');
return response;
}
return fetch(event.request).then(function(response){
console.log('Response from network is:', response);
return response;
});
}
)
})
);
});
在我的本地主机上,服务工作者完全正常 .
但是在服务器上返回的响应/承诺
return cache.match(event.request)
永远是 undefined . 因此,资源永远不会从缓存中提供,而是始终从网络提供 .
即使在Chrome的开发工具“应用程序”选项卡中,我也可以看到新服务工作者的注册工作正常,“缓存存储”充满了我的新缓存资源(请求URL到index.html和app.js) . 我还认为我已经使用Cache-Control no-cache正确处理了Web服务器配置调整 .
如果我改变
return cache.match(event.request)
至
return cache.match(event.request.url)
服务工作者也可以在服务器上工作 .
但是,我想了解为什么看起来正确的语法并且在我能找到的所有示例中使用的语法在服务器上不起作用 .
一个区别是我通过https直接访问localhost和服务器 .
编辑:另一个区别是来自服务器的资源被压缩(Header => content-encoding:gzip) .
它可以与这些差异之一联系起来吗?
任何想法都非常感谢!
1 回答
1.无缓存
尝试取消服务器中的缓存机制,我在远程Apache服务器中找到这些代码(通过HTTPS提供):
我的localhost不是通过HTTPS提供的,示例How to Setup a Basic Service Worker可以正常工作 .
2.匹配方法
Cache.match() - Web APIs | MDN显示该参数应该是您尝试在缓存中查找的请求 . 但
cache.match(event.request.url)
在localhost和远程Apache Server中也可以正常工作 . 缓存没有问题 .3. Gzip
在localhost(没有gzip)和远程Apache服务器(gzip)中测试之后,两个缓存文件都没有任何错误 . 所以gzip不是其中一个原因 .