【发布时间】:2019-08-07 12:12:51
【问题描述】:
我使用服务人员离线提供内容。以下代码运行良好,除非我在以在线模式打开和安装 serviceworker 后立即以离线模式刷新页面。 所有这些场景都有效: 1.在线加载页面,在线刷新页面->离线刷新页面-有效。 2. 在线加载“/offline-test/” -> 离线加载“/offline-test/index.html” - 有效 3. 在线加载“/offline-test/index.html/” -> 离线加载“/offline-test/” - 有效 只有这种情况不起作用: 在线加载页面 -> 在离线模式下刷新页面。
为什么?
我正在使用 Chrome 开发工具来模拟离线模式。 Firefox 中的同样问题(加载页面后关闭 WiFi)。
index.html
<HTML>
...
<BODY>
...
</BODY>
<SCRIPT>
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('../sw.js')
.then(function() {
console.log("Service Worker Registered");
});
}
</SCRIPT>
</HTML>
sw.js
self.addEventListener('install', function(e) {
// self.skipWaiting();
if(navigator.onLine) {
console.log('Navigator is online');
e.waitUntil(caches.keys()
.then(function(keyList) {
console.log('Try to delete cache.');
return Promise.all(keyList.map(function(key) {
return caches.delete(key)
.then(function(response) {
console.log('Cache-Key '+key+' will be deleted');
return response;
}, function(reject) {
consoloe.log('Failure deleting '+key);
return reject;
});
}))
})
);
}
e.waitUntil(
caches.open('offline-test-v3').then(function(cache) {
console.log('index.html and all the others will be added to cache');
return cache.addAll([
'offline-test/',
'offline-test/index.html',
'offline-test/style.css',
'offline-test/logo-192.png',
'offline-test/fonts/ROCK.TTF',
'manifest.json',
'offline-test/favicon.ico'
])
.then(function(response) {
console.log('Everything succesfully added to cache');
});
})
);
});
self.addEventListener('activate', function(ev) {
// ev.waitUntil(self.clients.claim());
// clients.claim();
// ev.waitUntil(clients.claim());
console.log('I\'m activated');
});
self.addEventListener('update', function(eve) {
console.log('I\'m updated');
});
self.addEventListener('fetch', function(event) {
console.log('Will fetch '+event.request.url);
//Networ first
event.respondWith(
fetch(event.request).catch(function() {
console.log('Try to fetch '+event.request.url+' from cache');
return caches.match(event.request);
})
);
在线加载 index.html 后的控制台
Service Worker Registered
sw.js:9 Navigator is online
sw.js:12 Try to delete cache.
sw.js:29 index.html and all the others will be added to cache
sw.js:40 Everything succesfully added to cache
sw.js:58 I'm activated
离线模式下刷新后的控制台
Will fetch index.html
sw.js:70 Try to fetch [url]/index.html from cache
The FetchEvent for [url]/index.html" resulted in a network error response: an object that was not a Response was passed to respondWith().
【问题讨论】:
标签: javascript caching service-worker page-refresh