我的应用程序使用请求数量有限的 API 从另一台服务器接收数据。数据很少更改,但即使在刷新页面后也可能需要更改。
- 使用 cookie 或 HTML5 WebStorage 的最佳解决方案是什么?
- 并且可能有其他方法来解决这个任务?
我的应用程序使用请求数量有限的 API 从另一台服务器接收数据。数据很少更改,但即使在刷新页面后也可能需要更改。
As much as cross browser compatibility matters, cookie
is the only choice rather than web storage.
But the question really depends on what kind of data you are caching?
For what you are trying, cookie and web-storage might not be needed at all.
I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.
Update:
Quoting:
data about user activity in some social networks (fb, vk, google+)
Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example
if (Modernizr.localstorage) {
// browser supports local storage
// Use this method
} else {
// browser doesn't support local storage
// Use Cookie Method
}
我写了这个库来解决同样的问题:
使用 Javascript 使用 cacheJS 缓存您的数据
以下是一些基本用法
// just add new cache using array as key
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:1,type:'json'}, jsonData);
// remove cache using key
cacheJS.removeByKey({blogId:1,type:'json'});
// add cache with ttl and contextual key
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', 3600, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd'});
// remove cache with con textual key
// cache for blog 2 and 3 will be removed
cacheJS.removeByContext({author:'hoangnd'})
这是一个从 JQuery AJAX 缓存数据的示例。因此,如果您只想在还没有数据时拨打电话,那真的很简单。只需这样做(示例)。在这里,我们首先检查我们是否有负载信息(键入在线、位置和发货日期),只有当我们没有时,我们才进行 AJAX 调用并将该数据放入缓存中:
var dict = [];
function checkCachedLoadLine(line, location, shipDate, callback) {
var ret = 0;
if(!((line+location+shipDate) in dict)) {
productionLineService.getProductionLoadLine(line, location, shipDate, callback);
}
return dict[line+location+shipDate];
}
...然后在回调中将值写入缓存
function callback(data) {
if (!data) {
document.getElementById('htmlid').innerHTML = 'N/A';
} else {
document.getElementById('htmlid').innerHTML = data[0];
dict[data[2]+data[3]+data[4]] = data[0];
}
}