Хри*_*тов 1 caching response fetch progressive-web-apps
我正在使用缓存存储来构建渐进式Web应用程序(PWA).我需要将一个自定义对象放入缓存中,但缓存接受Response对象作为参数.所以我的问题是如何正确创建具有JSON的Response对象.我知道我可以使用其他缓存策略(localStorage或IndexedDB),但我对这种情况特别好奇 - 将缓存中的自定义JSON保存为请求.
var myJSON = JSON.stringify({custom:"object"});
caches.open('cache-name').then(function (cache) {
var response = new Response(); //My JSON should go into this Response obj.
return cache.put('cache-name', response);
});
Run Code Online (Sandbox Code Playgroud)
Jef*_*ick 11
当然; 如果它对您的网络应用程序有意义,那么可以这样做.您可以在支持Cache Storage API的任何地方执行此操作,即在服务工作者中或从受控页面的上下文中执行.这是一个基本的例子:
const data = {
1: 2,
3: 4
};
const jsonResponse = new Response(JSON.stringify(data), {
headers: {
'content-type': 'application/json'
}
});
caches.open('json-cache').then(cache => cache.put('/data.json', jsonResponse));
Run Code Online (Sandbox Code Playgroud)
您可以通过记录类似的方式手动确认您希望存储的数据
caches.match('/data.json').then(r => r.json()).then(console.log)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1216 次 |
| 最近记录: |