原文地址: https://github.com/dwqs/blog/issues/42
在客戶端(瀏覽器端)存儲數據有諸多益處,最主要的一點是能快速訪問(網頁)數據。(以往)在客戶端有五種數據存儲方法,而目前就只有四種常用方法了(其中一種被廢棄了):
Cookies
Local Storage
Session Storage
IndexedDB
WebSQL (被廢棄)
Cookies
Cookies 是一種在文檔內存儲字符串數據最典型的方式。一般而言,cookies 會由服務端發送給客戶端,客戶端存儲下來,然後在隨後讓請求中再發回給服務端。這可以用於諸如管理用戶會話,追蹤用戶信息等事情。
此外,客戶端也用使用 cookies 存儲數據。因而,cookies 常被用於存儲一些通用的數據,如用戶的首選項設置。
Cookies 的 基本CRUD 操作
通過下面的語法,我們可以創建,讀取,更新和刪除 cookies:
// Create
document.cookie = "user_name=Ire Aderinokun";
document.cookie = "user_age=25;max-age=31536000;secure";
// Read (All)
console.log( document.cookie );
// Update
document.cookie = "user_age=24;max-age=31536000;secure";
// Delete
document.cookie = "user_name=Ire Aderinokun;expires=Thu, 01 Jan 1970 00:00:01 GMT";
Cookies 的優點
能用於和服務端通信
當 cookie 快要自動過期時,我們可以重新設置而不是刪除
Cookies 的缺點
增加了文檔傳輸的負載
只能存儲少量的數據
只能存儲字符串
潛在的 安全問題
自從有 Web Storage API (Local and Session Storage),cookies 就不再被推薦用於存儲數據了
瀏覽器支持
所有主流瀏覽器均支持 Cookies.
Local Storage
Local Storage 是 Web Storage API 的一種類型,能在瀏覽器端存儲鍵值對數據。Local Storage 因提供了更直觀和安全的API來存儲簡單的數據,被視爲替代 Cookies 的一種解決方案。
從技術上說,儘管 Local Storage 只能存儲字符串,但是它也是可以存儲字符串化的JSON數據。這就意味着,Local Storage 能比 Cookies 存儲更復雜的數據。
Local Storage 的 基本CRUD 操作
通過下面的語法,我們可以創建,讀取,更新和刪除 Local Storage:
// Create
const user = { name: 'Ire Aderinokun', age: 25 }
localStorage.setItem('user', JSON.stringify(user));
// Read (Single)
console.log( JSON.parse(localStorage.getItem('user')) )
// Update
const updatedUser = { name: 'Ire Aderinokun', age: 24 }
localStorage.setItem('user', JSON.stringify(updatedUser));
// Delete
localStorage.removeItem('user');
Local Storage 的優點
相比於Cookies:
其提供了更直觀地接口來存儲數據
更安全
能存儲更多數據
Local Storage 的缺點
只能存儲字符串數據(直接存儲複合數據類型如數組/對象等,都會轉化成字符串,會存在存取數據不一致的情況):
localStorage.setItem('test',1);
console.log(typeof localStorage.getItem('test')) //"string"
localStorage.setItem('test2',[1,2,3]);
console.log(typeof localStorage.getItem('test2')) //"string"
console.log(localStorage.getItem('test2')) //"1,2,3"
localStorage.setItem('test3',{a:1,b:2});
console.log(typeof localStorage.getItem('test3')) //"string"
console.log(localStorage.getItem('test3')) //"[object object]"
//爲避免存取數據不一致的情形,存儲複合數據類型時進行序列化,讀取時進行反序列化
localStorage.setItem('test4', JSON.stringify({a:1,b:2}));
console.log(typeof localStorage.getItem('test4')) //"string"
console.log(JSON.parse(localStorage.getItem('test4'))) //{a:1,b:2}
瀏覽器支持
IE8+/Edge/Firefox 2+/Chrome/Safari 4+/Opera 11.5+(caniuse)
Session Storage
Session Storage 是 Web Storage API 的另一種類型。和 Local Storage 非常類似,區別是 Session Storage 只存儲當前會話頁(tab頁)的數據,一旦用戶關閉當前頁或者瀏覽器,數據就自動被清除掉了。
Session Storage 的 基本CRUD 操作
通過下面的語法,我們可以創建,讀取,更新和刪除 Session Storage:
// Create
const user = { name: 'Ire Aderinokun', age: 25 }
sessionStorage.setItem('user', JSON.stringify(user));
// Read (Single)
console.log( JSON.parse(sessionStorage.getItem('user')) )
// Update
const updatedUser = { name: 'Ire Aderinokun', age: 24 }
sessionStorage.setItem('user', JSON.stringify(updatedUser));
// Delete
sessionStorage.removeItem('user');
優點,缺點和瀏覽器支持
和 Local Storage 一樣
IndexedDB
IndexedDB 是一種更復雜和全面地客戶端數據存儲方案,它是基於 JavaScript、面向對象的和數據庫的,能非常容易地存儲數據和檢索已經建立關鍵字索引的數據。
在構建漸進式Web應用一文中,我已經介紹了怎麼使用 IndexedDB 來創建一個離線優先的應用。
IndexedDB 的基本 CRUD 操作
注:在示例中,我使用了 Jake's Archibald 的 IndexedDB Promised library, 它提供了 Promise 風格的IndexedDB方法
使用 IndexedDB 在瀏覽器端存儲數據比上述其它方法更復雜。在我們能創建/讀取/更新/刪除任何數據之前,首先需要先打開數據庫,創建我們需要的stores(類似於在數據庫中創建一個表)。
function OpenIDB() {
return idb.open('SampleDB', 1, function(upgradeDb) {
const users = upgradeDb.createObjectStore('users', {
keyPath: 'name'
});
});
}
創建或者更新store中的數據:
// 1. Open up the database
OpenIDB().then((db) => {
const dbStore = 'users';
// 2. Open a new read/write transaction with the store within the database
const transaction = db.transaction(dbStore, 'readwrite');
const store = transaction.objectStore(dbStore);
// 3. Add the data to the store
store.put({
name: 'Ire Aderinokun',
age: 25
});
// 4. Complete the transaction
return transaction.complete;
});
檢索數據:
// 1. Open up the database
OpenIDB().then((db) => {
const dbStore = 'users';
// 2. Open a new read-only transaction with the store within the database
const transaction = db.transaction(dbStore);
const store = transaction.objectStore(dbStore);
// 3. Return the data
return store.get('Ire Aderinokun');
}).then((item) => {
console.log(item);
})
刪除數據:
// 1. Open up the database
OpenIDB().then((db) => {
const dbStore = 'users';
// 2. Open a new read/write transaction with the store within the database
const transaction = db.transaction(dbStore, 'readwrite');
const store = transaction.objectStore(dbStore);
// 3. Delete the data corresponding to the passed key
store.delete('Ire Aderinokun');
// 4. Complete the transaction
return transaction.complete;
})
如果你有興趣瞭解更多關於IndexedDB的使用,可以閱讀我的這篇關於怎麼在漸進式Web應用(PWA)使用IndexedD。
IndexedDB 的優點
能夠處理更復雜和結構化的數據
每個'database'中可以有多個'databases'和'tables'
更大的存儲空間
對其有更多的交互控制
IndexedDB 的缺點
比 Web Storage API 更難於應用
瀏覽器支持
IE10+/Edge12+/Firefox 4+/Chrome 11+/Safari 7.1+/Opera 15+(caniuse)
對比
Feature | Cookies | Local Storage | Session Storage | IndexedDB |
---|---|---|---|---|
Storage Limit | ~4KB | ~5MB | ~5MB | Up to half of hard drive |
Persistent Data? | Yes | Yes | No | Yes |
Data Value | Type | String | String | String |
Indexable ? | No | No | No | Yes |
參考