我正在使用Service Worker离线工作。因此,对于每个获取请求,我将其存储在缓存中。
现在,
我希望服务工作者会提出请求,并将其存储下次。
问题是当我使用fetch(myUrl).then...
时,服务工作者中的Fetch Listener self.addEventListener('fetch', function(e)...
无法捕获它。
我不想复制代码..任何想法?
fetch侦听器是:
self.addEventListener(' fetch',function(e){
// e.respondWidth Responds to the fetch event
e.respondWith(
// Check in cache for the request being made
caches.match(e.request)
.then(function(response) {
// If the request is in the cache
if ( response ) {
console.log("[ServiceWorker] Found in Cache", e.request.url, response);
// Return the cached version
return response;
}
// If the request is NOT in the cache, fetch and cache
var requestClone = e.request.clone();
return fetch(requestClone)
.then(function(response) {
if ( !response ) {
console.log("[ServiceWorker] No response from fetch ")
return response;
}
var responseClone = response.clone();
// Open the cache
caches.open(cacheName).then(function(cache) {
// Put the fetched response in the cache
cache.put(e.request, responseClone);
console.log('[ServiceWorker] New Data Cached', e.request.url);
// Return the response
return response;
}); // end caches.open
// returns the fresh response (not cached..)
return response;
})
.catch(function(err) {
console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
});
}) // end caches.match(e.request)
.catch(function(e){
// this is - if we still dont have this in the cache !!!
console.log("[ServiceWorker] ERROR WITH THIS MATCH !!!",e, arguments)
})// enf of caches.match
); // end e.respondWith
});
答案 0 :(得分:0)
由于我无法评论获取任何具体细节,而您的代码对我来说似乎是正确的,我的猜测是:
答案 1 :(得分:0)
然后可能正在寻找缓存然后网络策略:
var networkDataReceived = false;
startSpinner();
// fetch fresh data
var networkUpdate = fetch('/data.json').then(function(response) {
return response.json();
}).then(function(data) {
networkDataReceived = true;
updatePage();
});
// fetch cached data
caches.match('/data.json').then(function(response) {
if (!response) throw Error("No data");
return response.json();
}).then(function(data) {
// don't overwrite newer network data
if (!networkDataReceived) {
updatePage(data);
}
}).catch(function() {
// we didn't get cached data, the network is our last hope:
return networkUpdate;
}).catch(showErrorMessage).then(stopSpinner);