客戶端(瀏覽器端)數(shù)據(jù)存儲技術(shù)概覽
在客戶端(瀏覽器端)存儲數(shù)據(jù)有諸多益處,最主要的一點是能快速訪問(網(wǎng)頁)數(shù)據(jù)。(以往)在客戶端有五種數(shù)據(jù)存儲方法,而目前就只有四種常用方法了(其中一種被廢棄了):
- Cookies
- Local Storage
- Session Storage
- IndexedDB
- WebSQL (被廢棄)
Cookies
Cookies 是一種在文檔內(nèi)存儲字符串數(shù)據(jù)最典型的方式。一般而言,cookies 會由服務(wù)端發(fā)送給客戶端,客戶端存儲下來,然后在隨后讓請求中再發(fā)回給服務(wù)端。這可以用于諸如管理用戶會話,追蹤用戶信息等事情。
此外,客戶端也用使用 cookies 存儲數(shù)據(jù)。因而,cookies 常被用于存儲一些通用的數(shù)據(jù),如用戶的***項設(shè)置。
Cookies 的 基本CRUD 操作
通過下面的語法,我們可以創(chuàng)建,讀取,更新和刪除 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 的優(yōu)點
- 能用于和服務(wù)端通信
- 當 cookie 快要自動過期時,我們可以重新設(shè)置而不是刪除
Cookies 的缺點
- 增加了文檔傳輸?shù)呢撦d
- 只能存儲少量的數(shù)據(jù)
- 只能存儲字符串
- 潛在的 安全問題
- 自從有 Web Storage API (Local and Session Storage),cookies 就不再被推薦用于存儲數(shù)據(jù)了
瀏覽器支持
所有主流瀏覽器均支持 Cookies.
Local Storage
Local Storage 是 Web Storage API 的一種類型,能在瀏覽器端存儲鍵值對數(shù)據(jù)。Local Storage 因提供了更直觀和安全的API來存儲簡單的數(shù)據(jù),被視為替代 Cookies 的一種解決方案。
從技術(shù)上說,盡管 Local Storage 只能存儲字符串,但是它也是可以存儲字符串化的JSON數(shù)據(jù)。這就意味著,Local Storage 能比 Cookies 存儲更復(fù)雜的數(shù)據(jù)。
Local Storage 的 基本CRUD 操作
通過下面的語法,我們可以創(chuàng)建,讀取,更新和刪除 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 的優(yōu)點
相比于Cookies:
- 其提供了更直觀地接口來存儲數(shù)據(jù)
- 更安全
- 能存儲更多數(shù)據(jù)
Local Storage 的缺點
- 只能存儲字符串數(shù)據(jù)(直接存儲復(fù)合數(shù)據(jù)類型如數(shù)組/對象等,都會轉(zhuǎn)化成字符串,會存在存取數(shù)據(jù)不一致的情況):
- 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]"
- //為避免存取數(shù)據(jù)不一致的情形,存儲復(fù)合數(shù)據(jù)類型時進行序列化,讀取時進行反序列化
- 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 非常類似,區(qū)別是 Session Storage 只存儲當前會話頁(tab頁)的數(shù)據(jù),一旦用戶關(guān)閉當前頁或者瀏覽器,數(shù)據(jù)就自動被清除掉了。
Session Storage 的 基本CRUD 操作
通過下面的語法,我們可以創(chuàng)建,讀取,更新和刪除 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');
優(yōu)點,缺點和瀏覽器支持
和 Local Storage 一樣
IndexedDB
IndexedDB 是一種更復(fù)雜和全面地客戶端數(shù)據(jù)存儲方案,它是基于 JavaScript、面向?qū)ο蟮暮蛿?shù)據(jù)庫的,能非常容易地存儲數(shù)據(jù)和檢索已經(jīng)建立關(guān)鍵字索引的數(shù)據(jù)。
在構(gòu)建漸進式Web應(yīng)用一文中,我已經(jīng)介紹了怎么使用 IndexedDB 來創(chuàng)建一個離線優(yōu)先的應(yīng)用。
IndexedDB 的基本 CRUD 操作
注:在示例中,我使用了 Jake’s Archibald 的 IndexedDB Promised library, 它提供了 Promise 風(fēng)格的IndexedDB方法
使用 IndexedDB 在瀏覽器端存儲數(shù)據(jù)比上述其它方法更復(fù)雜。在我們能創(chuàng)建/讀取/更新/刪除任何數(shù)據(jù)之前,首先需要先打開數(shù)據(jù)庫,創(chuàng)建我們需要的stores(類似于在數(shù)據(jù)庫中創(chuàng)建一個表)。
- function OpenIDB() {
- return idb.open('SampleDB', 1, function(upgradeDb) {
- const users = upgradeDb.createObjectStore('users', {
- keyPath: 'name'
- });
- });
- }
創(chuàng)建或者更新store中的數(shù)據(jù):
- // 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;
- });
檢索數(shù)據(jù):
- // 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);
- })
刪除數(shù)據(jù):
- // 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;
- })
如果你有興趣了解更多關(guān)于IndexedDB的使用,可以閱讀我的這篇關(guān)于怎么在漸進式Web應(yīng)用(PWA)使用IndexedD。
IndexedDB 的優(yōu)點
- 能夠處理更復(fù)雜和結(jié)構(gòu)化的數(shù)據(jù)
- 每個’database’中可以有多個’databases’和’tables’
- 更大的存儲空間
- 對其有更多的交互控制
IndexedDB 的缺點
- 比 Web Storage API 更難于應(yīng)用
瀏覽器支持
IE10+/Edge12+/Firefox 4+/Chrome 11+/Safari 7.1+/Opera 15+(caniuse)
對比
參考
An Overview of Client-Side Storage(https://bitsofco.de/an-overview-of-client-side-storage/)