先看看各種本地儲存方案的演進:
Cookies:瀏覽器均支援,容量為 4KB
UserData:僅 IE 支援,容量為 64KB
Flash:100KB
Google Gears SQLite:需要外掛支援,容量無限制
LocalStorage:HTML5,容量為 5M
現在我們準備在專案中用來取代 Cookie,基本分析如下:
每次與伺服器端互動,Cookie 都會在請求中被攜帶,Cookie 過多也造成頻寬浪費;
Cookie 容量很小,或許無法滿足當今互聯網的本地儲存需求;
在 IE8+、Firefox 3.0+、Opera 10.5+、Chrome 4.0+、Safari 4.0+、iPhone 2.0+、Android 2.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 內核),因此也支援 LocalStorage;最後只剩 IE7 及以下版本,對它們就用自家的 UserData,處理很方便。結論:用 UserData 與 HTML5 LocalStorage 結合的方式,來取代 Cookie!
UserData 行為透過將資料寫入一個 UserData 儲存區(UserData store)來保存資料,它可以把資料以 XML 格式保存在客戶端電腦上。該資料將一直存在,除非你人為刪除或用腳本設定了失效期。從表格可以看出,就算是受限(Restricted)的站點,單個文件也能存 64KB 資料,整個 Domain 也能裝得下 640KB。
我們都知道,用 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 的方式保存到本地
* @param {String} key 待儲存資料的 key
* @param {Object} config 待儲存資料相關配置
* @config {String} key 待儲存資料的 key
* @config {String} value 待儲存資料的內容
* @config {String|Object} [expires] 資料的過期時間
* @private
*/
function __setItem(key,config){
try {
var input = _getInstance();
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);
//存儲到本地文件
input.save(storageInfo.key);
} catch (e) {
}
}
再看 userData 本地資料的讀取:
/**
* 提取本地儲存的資料
* @param {String} config 待獲取的儲存資料相關配置
* @return {String} 本地儲存的資料,獲取不到時返回 null
* @private
*/
function _getItem(config){
try {
var input = _getInstance();
//載入本地文件
input.load(config.key);
//取得資料
return input.getAttribute(config.key) || null;
} catch (e) {
return null;
}
}
模擬 remove 操作:
/**
* 移除某項儲存資料
* @param {Object} config 配置參數
* @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);
//下面的程式碼用來記錄當前保存的 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;
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:
getAllKeys : function(){
var result = [];
//支持本地儲存的瀏覽器:IE8+、Firefox3.0+、Opera10.5+、Chrome4.0+、Safari4.0+、iPhone2.0+、Android2.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、清除所有本地儲存的資料:
clearAll : function(){
//支持本地儲存的瀏覽器:IE8+、Firefox3.0+、Opera10.5+、Chrome4.0+、Safari4.0+、iPhone2.0+、Android2.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.getAllKeys
// 獲取所有本地儲存的 key
var keys = qext.LocalStorage.getAllKeys();