我刚刚尝试实现服务工作者在静态站点上缓存一些JSON文件和其他资产(在localhost chrome版本47.0.2526.73(64位)上运行).使用cache.addAll()我已将文件添加到缓存中,当我打开chrome中的资源选项卡,然后单击缓存存储时,将列出所有文件.
我遇到的问题是我的服务工作者在chrome:// service-worker-internals中被列为"激活"和"正在运行"但是,我无法确定该工作者是否实际上正在拦截请求并提供缓存文件.我添加了事件监听器,即使我在服务工作者开发工具实例中控制日志事件,它也永远不会遇到断点:
this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
console.log(cache);
return cache.addAll([
'/json/0.json',
'/json/1.json',
'/json/3.json',
'/json/4.json',
'/json/5.json',
]);
})
);
});
this.addEventListener('fetch', function(event) {
console.log(event);
var response;
event.respondWith(caches.match(event.request).catch(function() {
return fetch(event.request);
}).then(function(r) {
response = r;
caches.open('v1').then(function(cache) {
cache.put(event.request, response);
});
return response.clone();
}).catch(function() {
}));
});
Run Code Online (Sandbox Code Playgroud)
基本上我正在完成HTML5摇滚服务工作者介绍中描述的事情,但我很确定我的资产不是从缓存中提供的.我已经注意到,服务工作者提供的资产在size列中的devtools的网络选项卡中通过指示"来自服务工作者"来注明.
看起来好像我的代码与示例没什么不同,但是由于某些原因它并没有达到fetch事件.我的代码的要点:https://gist.github.com/srhise/c2099b347f68b958884d
javascript google-chrome service-worker progressive-web-apps