问题描述
我在我的 service worker 中使用了以下逻辑(用我自己的话来说):
I'm using the following logic in my service worker (in my own words):
如果缓存存在,使用它,但也从网络更新缓存以备后用
event.respondWith( // on `fetch`
caches.open(CACHE)
.then(function(cache) {
return cache.match(request);
})
.then(function(matching) {
if (matching) {
requestAndUpdateCache(event);
return matching;
}
...
除了使用缓存的响应进行响应之外,我还运行了这个名为 requestAndUpdateCache
的函数.
In addition to responding with the cached response, I also run this function called requestAndUpdateCache
.
function requestAndUpdateCache(event){
var url = event.request.url + '?t=' + new Date().getTime();
fetch(url)
.then(function(response){
if (response && response.status === 200){
caches.open(CACHE)
.then(function(cache){
cache.put(event.request, response.clone());
});
}
}, function(error){
console.log(error);
});
}
问题:此功能及其位置对于完成上述逻辑是否有意义?
Questions: Does this function and its placement make sense to accomplish the logic outlined above?
推荐答案
您所描述的是一种陈旧的同时重新验证策略.
What you're describing is a stale-while-revalidate strategy.
寻找不同 Service Worker 缓存策略实现的规范位置是 Jake Archibald 的 离线食谱.有一个部分涵盖 stale-while-revalidate,包括以下代码:
The canonical place to look for implementations of different service worker caching strategies is Jake Archibald's The Offline Cookbook. There's a section that covers stale-while-revalidate, including the following code:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open('mysite-dynamic').then(function(cache) {
return cache.match(event.request).then(function(response) {
var fetchPromise = fetch(event.request).then(function(networkResponse) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
})
return response || fetchPromise;
})
})
);
});
这篇关于Service Worker 从缓存中获取然后更新缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!