当与服务器没有连接时,从缓存返回响应
Returning response from cache when there is no connection to server
在service worker的帮助下,如果没有连接到服务器,我想从缓存返回响应。然后,如果缓存中没有正确的响应,我希望返回自定义响应。
现在,我有这样的代码:
this.addEventListener('fetch', function (event) {
event.respondWith(
timeout(5000, fetch(event.request)).catch(function() {
return caches.match(event.request);
})
);
});
我想有这样的东西:
this.addEventListener('fetch', function (event) {
event.respondWith(
timeout(5000, fetch(event.request)).catch(function() {
caches.match(event.request).then(function(cacheResponse) {
return cacheResponse;
}).catch(function () {
return new Response('No cache found');
})
})
);
});
或者更好的是
this.addEventListener('fetch', function (event) {
event.respondWith(
timeout(5000, fetch(event.request)).catch(function() {
caches.match(event.request).then(function(cacheResponse) {
return cacheResponse;
}).catch(function () {
return caches.match(offlineMessageUrl);
})
})
);
});
从缓存的文档中。匹配函数,承诺总是被解决。使用Response对象解析,如果没有找到匹配,则使用undefined解析。你可以试试这个:-
this.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function(cacheResponse) {
return cacheResponse || new Response('No cache found');
}).catch(function () {
return new Response('No cache found');
})
);
});
相关文章:
- 节点导出返回一个空对象
- ES6构造函数返回基类的实例
- 监视函数从服务返回不起作用,但作用域函数起作用
- 控制台返回var不是't定义,但它是
- 从函数返回角度承诺
- Sammy.js缓存和滚动位置时,返回历史
- 当用户返回 UC 浏览器时,如何以编程方式禁用缓存
- 在Angularjs服务中为返回对象引用的http请求提供的数据构建简单的缓存
- 当用户离线时使用角度 js 返回缓存响应
- $('#textboxId').val() 返回旧值(浏览器缓存问题)
- 如何从缓存或 ajax 加载中返回模板
- JavaScript内存化只能用于缓存返回的结果吗
- JQuery getJson方法第一次返回缓存的数据
- IIS上的AngularJS -浏览器缓存不返回更新后的页面模板
- iOS 5 Safari中页面缓存的问题,当导航返回/卸载事件未触发时
- Http fetch返回缓存的数据
- 如何使用PhoneGap缓存谷歌地图返回的静态地图
- JavaScript缓存返回值的函数有多个参数
- 吞下我可观察到的错误并返回缓存值——所有这些都可以保持订阅的活力
- 当与服务器没有连接时,从缓存返回响应