2012-10-07 78 views
6

我的應用程序使用API​​數量有限的請求從另一個服務器接收數據。數據變化很少,但即使在刷新頁面之後也可能是必需的。在客戶端使用js緩存數據的最佳方式是什麼?

  1. 什麼是最好的解決方案這個問題,使用Cookie或HTML5 WebStorage?
  2. 而且可能有別的辦法來解決這個任務?

回答

5

儘管跨瀏覽器兼容性問題,cookie是唯一的選擇,而不是網絡存儲。

但這個問題真的取決於你要緩存什麼樣的數據?

對於您所嘗試的,可能根本不需要cookie和網絡存儲。

  • Cookie用於存儲配置相關信息,而不是實際數據本身。
  • 網絡存儲支持持久性數據存儲,與Cookie類似,但容量大大增強,並且HTTP請求標頭中沒有信息存儲。 [1]

我寧願說,這將是愚蠢的緩存整個頁面,Cookie或網絡存儲兩者。出於這些目的,服務器端緩存選項可能是更好的方法。

更新:

引用:

關於用戶活動的數據在某些社交網絡(FB,VK,谷歌+)

檢測所述網絡的存儲功能,使用庫如mordernizr,如果不存在則回退到cookie方法。 一個簡單的例子

if (Modernizr.localstorage) { 
    // browser supports local storage 
    // Use this method 
} else { 
    // browser doesn't support local storage 
    // Use Cookie Method 
} 

[1]:http://en.wikipedia.org/wiki/Web_storage

+0

什麼樣的數據......嗯。例如,有關某些社交網絡(fb,vk,google +)中用戶活動的數據。在服務器端緩存數據對我來說非常糟糕,因爲這麼多的數據=)這個應用程序的跨瀏覽器兼容性不是主要任務,這個應用程序爲現代瀏覽器。 – artzub

+0

@artzub,檢查我的更新 – Starx

+0

Thx,我看它! – artzub

4

我寫這個LIB解決同樣的問題:

Cache your data with Javascript using 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'})

相關問題