d-_*_*_-b 1 javascript caching service-worker
我在服务工作者中使用以下逻辑(用我自己的话说):
如果存在缓存,请使用它,但也可以从网络更新缓存以供日后使用
event.respondWith( // on `fetch`
caches.open(CACHE)
.then(function(cache) {
return cache.match(request);
})
.then(function(matching) {
if (matching) {
requestAndUpdateCache(event);
return matching;
}
...
Run Code Online (Sandbox Code Playgroud)
除了响应缓存的响应之外,我还运行了这个函数调用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);
});
}
Run Code Online (Sandbox Code Playgroud)
问题:这个功能及其位置是否有助于完成上述逻辑?
您所描述的是一种陈旧的重新验证策略.
寻找不同服务工作者缓存策略实现的规范场所是Jake Archibald的The Offline Cookbook.有一个部分涵盖了stale-while-revalidate,包括以下代码:
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;
})
})
);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
912 次 |
| 最近记录: |