4
我有一個服務工作人員爲我的網站,但我不知道如何讓它處理有網絡錯誤時,我瀏覽過Mozilla的指南,但是當我運行工作人員離線它說網絡錯誤被傳遞給respondWith
函數,並且catch語句似乎沒有響應緩存數據。使用服務人員來捕捉網絡錯誤
this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll([
'/',
'/favicon.ico',
'/f3be2e30f119a1a9b0fdee9fc1f477a9',
'/index.html',
'/sw.js'
]);
})
);
});
this.addEventListener('fetch', function(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(event) {
console.log(event, 'borken');
return caches.match(event.request);
});
});