背景
先看看各種本地存儲的變革:
Cookies:瀏覽器均支持,容量為4KB
UserData:僅IE支持,容量為64KB
Flash:100KB
Google Gears SQLite :需要插件支持,容量無限制
LocalStorage:HTML5,容量為5M
現準備在項目中試圖取代cookie的實現,基本分析如下:
每次和服務器端進行交互,cookie都會在請求中被攜帶,cookie過多,也造成帶寬的浪費
cookie的容量很小,或許無法滿足當今互聯網的本地存儲需求
在IE8+、Firefox3.0+、Opera10.5+、Chrome4.0+、Safari4.0+、iphone2.0+、Andrioid2.0+等平臺下,已經完全支持HTML5的LocalStorage
在IE7即以下版本中,可以使用UserData來代替cookie,而且同樣比cookie保險
用戶可能清cookie,但不見得知道去清UserData或者LocalStorage,這也增強了一道代碼保險
到底用啥來取代?
UserData:僅IE可用
Flash:存儲空間夠了,也還挺好,可這玩意兒不是HTML原生的
Google Gears:存儲空間沒啥限制,就是得裝額外的插件
HTML5-LocalStorage:官方建議每個站點可以本地存儲5M的內容,非常大了
最后再分析一下現在咱們針對的瀏覽器:IE系列、FF、Chrome、Safari、Opera,外加雙核的遨游、QQ瀏覽器、搜狗瀏覽器
其中,現在的FF、Chrome、Safari、Opera已經完全支持HTML5-LocalStorage
雙核的那些個瀏覽器,要么Webkit內核,要么IE內核(大多都是IE8的內核了),所以這些也是支持HTML5-LocalStorage的
最后就剩IE7及其以下版本,對于專門的IE,就用它們自家提供的UserData了,處理很方便
總結:用UserData和HTML5-LocalStorage結合的方式,來取代cookie!
UserData的存儲情況:
2011-03-23_201627.png
UserData行為通過將數據寫入一個UserData存儲區(UserData store)來保存數據,userData可以將數據以xml格式保存在客戶端計算機上。
該數據將一直存在,除非你人為刪除或者用腳本設置了該數據的失效期。
從上面的表格可以看出,就算是一個受限(Restricted)的站點,單個文檔也能存64KB的數據,整個Domain也能裝得下640KB的東西。
要了解更多UserData的東西,可以點擊這里
關于Expires
我們都知道,采用cookie來進行本地數據緩存,可以設定一個生命周期,在IE中采用UserData進行替代,能完美的實現。
但是對于HTML5提供的LocalStorage則沒有提供現成的API,來設置某本地存儲的生命周期,只能采取一些極端的手段進行模擬實現。
關于數據的批量存儲、提取、刪除
一個好用的組件庫,應該提供更加便捷的API,原生的cookie、UserData、LocalStorage都沒有提供現成的接口可調用,所以,在這里,我們來包裝一個,使其擁有這樣的批量接口。
代碼實現
1、IE中的UserData實現
原理很簡單,就是創建一個HTML節點,為其增加一個行為(behavior):#default#userData,把待存儲的數據放到該節點的屬性上(setAttribute),再保存到本地即可(save)。
創建html實例:
/**
* 創建并獲取這個input:hidden實例
* @return {HTMLInputElement} input:hidden實例
* @PRivate
*/
function _getInstance(){
 //把UserData綁定到input:hidden上
 var _input = null;
 //是的,不要驚訝,這里每次都會創建一個input:hidden并增加到DOM樹種
 //目的是避免數據被重復寫入,提早造成“磁盤空間寫滿”的Exception
 _input = document.createElement("input");
 _input.type = "hidden";
 _input.addBehavior("#default#userData");
 document.body.appendChild(_input);
 return _input;
}
本地數據存儲:
/**
* 將數據通過UserData的方式保存到本地,文件名為:文件名為:config.key[1].xml
* @param {String} key 待存儲數據的key,和config參數中的key是一樣的
* @param {Object} config 待存儲數據相關配置
* @cofnig {String} key 待存儲數據的key
* @config {String} value 待存儲數據的內容
* @config {String|Object} [expires] 數據的過期時間,可以是數字,單位是毫秒;也可以是日期對象,表示過期時間
* @private
*/
function __setItem(key,config){
 try {
 var input = _getInstance();
 //創建一個Storage對象
 var storageInfo = config || {};
 //設置過期時間
 if(storageInfo.expires) {
 var expires;
 //如果設置項里的expires為數字,則表示數據的能存活的毫秒數
 if ('number' == typeof storageInfo.expires) {
 expires = new Date();
 expires.setTime(expires.getTime() + storageInfo.expires);
 }
 input.expires = expires.toUTCString();
 }
 //存儲數據
 input.setAttribute(storageInfo.key,storageInfo.value);
 //存儲到本地文件,文件名為:storageInfo.key[1].xml
 input.save(storageInfo.key);
 }catch(e) {
 }
}
再看userData本地數據的讀取:
/**
* 提取本地存儲的數據
* @param {String} config 待獲取的存儲數據相關配置
* @cofnig {String} key 待獲取的數據的key
* @return {String} 本地存儲的數據,獲取不到時返回null
* @example
* qext.LocalStorage.get({
* key : "username"
* });
* @private
*/
function _getItem(config){
 try {
 var input = _getInstance();
 //載入本地文件,文件名為:config.key[1].xml
 input.load(config.key);
 //取得數據
 return input.getAttribute(config.key) || null;
 } catch (e) {
 return null;
 }
}
模擬remove操作:
/**
* 移除某項存儲數據
* @param {Object} config 配置參數
* @cofnig {String} key 待存儲數據的key
* @private
*/
function _removeItem(config){
 try {
 var input = _getInstance();
 //載入存儲區塊
 input.load(config.key);
 //移除配置項
 input.removeAttribute(config.key);
 //強制使其過期
 var expires = new Date();
 expires.setTime(expires.getTime() - 1);
 input.expires = expires.toUTCString();
 input.save(config.key);
 //從allkey中刪除當前key
 //下面的代碼用來記錄當前保存的key,便于以后clearAll
 var result = _getItem({key : _clearAllKey});
 if(result) {
 result = result.replace(new RegExp("(^||)" + config.key + "(||$)",'g'),'');
 result = {
 key : _clearAllKey,
 value : result
 };
 //保存鍵
 __setItem(_clearAllKey,result);
 }
 } catch (e) {
 }
}
2、再看HTML5-LocalStorage中expires的模擬:
在進行數據存儲的時候,單獨多存一個字段:key + ".expires",如果傳入的expires為數字類型,單位則是毫秒(ms)
window.localStorage.setItem(storageInfo.key,storageInfo.value);
// 如果需要指定生命周期
if(config.expires) {
 var expires;
 //如果設置項里的expires為數字,則表示數據的能存活的毫秒數
 if ('number' == typeof storageInfo.expires) {
 expires = new Date();
 expires.setTime(expires.getTime() + storageInfo.expires);
 }
 window.localStorage.setItem(storageInfo.key + ".expires",expires);
}
在數據讀取的時候,通用讀取這個字段,判斷時間是否超出了生命周期
result = window.localStorage.getItem(config.key);
//過期時間判斷,如果過期了,則移除該項
if(result) {
 var expires = window.localStorage.getItem(config.key + ".expires");
 result = {
 value : result,
 expires : expires ? new Date(expires) : null
 };
 if(result && result.expires && result.expires < new Date()) {
 result = null;
 window.localStorage.removeItem(config.key);
 }
}
3、提取所有key
/**
* 獲取所有的本地存儲數據對應的key
* <pre><code>
* var keys = qext.LocalStorage.getAllKeys();
* </code></pre>
* @return {Array} 所有的key
*/
getAllKeys : function(){
 var result = [];
 //支持本地存儲的瀏覽器:IE8+、Firefox3.0+、Opera10.5+、Chrome4.0+、Safari4.0+、iPhone2.0+、Andrioid2.0+
 if(_isSupportLocalStorage) {
 var key;
 for(var i = 0,len = window.localStorage.length;i < len;i++){
 key = window.localStorage.key(i);
 if(!/.+.expires$/.test(key)) {
 result.push(key);
 }
 }
 } else if(_isSupportUserData) { //IE7及以下版本,采用UserData方式
 result = _getAllKeys();
 }
 return result;
}
4、清除所有本地存儲的數據
/**
* 清除所有本地存儲的數據
* <pre><code>
* qext.LocalStorage.clearAll();
* </code></pre>
*/
clearAll : function(){
 //支持本地存儲的瀏覽器:IE8+、Firefox3.0+、Opera10.5+、Chrome4.0+、Safari4.0+、iPhone2.0+、Andrioid2.0+
 if(_isSupportLocalStorage) {
 window.localStorage.clear();
 } else if(_isSupportUserData) { //IE7及以下版本,采用UserData方式
 _clearAll();
 }
}
關于使用方法
1、數據存儲:qext.LocalStorage.set
// 保存單個對象到本地
qext.LocalStorage.set({
 key : "username",
 value : "baiduie",
 expires : 3600 * 1000 /*單位:ms*/
});
// 保存多個對象
qext.LocalStorage.set([{
 key : "username",
 value : "baiduie",
 expires : 3600 * 1000 /*單位:ms*/
},{
 key : "passWord",
 value : "zxlie",
 expires : 3600 * 1000 /*單位:ms*/
}]);
2、數據提取:qext.LocalStorage.get
//獲取某一個本地存儲,返回值為:{key:"",value:"",expires:""},未取到值時返回值為:null
var rst = qext.LocalStorage.get({
 key : "username"
});
//獲取多個本地存儲,返回值為:["","",""],未取到值時返回值為:[null,null,null]
qext.LocalStorage.get([{
 key : "username"
},{
 key : "password"
},{
 key : "sex"
}]);
3、數據刪除:qext.LocalStorage.remove
//刪除一個本地存儲項
qext.LocalStorage.remove({
 key : "username"
});
//刪除多個本地存儲項目
qext.LocalStorage.remove([{
 key : "username"
},{
 key : "password"
},{
 key : "sex"
}]);
4、清空所有數據:qext.LocalStorage.clearAll
// 清空所有本地存儲的數據
qext.LocalStorage.clearAll();
5、獲取所有本地存儲的key:qext.LocalStorage.getAllKes
// 獲取所有本地存儲的key
var keys = qext.LocalStorage.getAllKeys();
新聞熱點
疑難解答