[译]本地存储的概述

在浏览器内直接存储数据有很多好处,最主要的是快以及独立于网络去访问“数据库”,目前有四种方法(加上一个弃用),将数据存储在客户端:

  1. Cookies
  2. Local Storage
  3. Session Storage
  4. IndexedDB
  5. WebSQL (弃用)

Cookies

Cookies 是经典的存储数据方式,把简单的字符串数据储存在一个文档里。通常情况下,Cookies从服务器被发送到客户机,然后储存,并在后续请求中发送回服务器。这可以用于管理账户和跟踪用户信息。

另外,Cookies可以完全在客户端存储数据,正因为如此,它们也被用于存储通用数据如用户偏好。

Cookies实现基本的CRUD

我们可以创建、读取、更新和删除cookie使用以下语法:

// 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的优点

  • 可以用于与服务器通信
  • 可以设置自动到期,而不必手动删除

Cookies的缺点

  • Cookie数量和长度有限制
  • 只能储存字符串
  • 潜在的安全问题
  • 自从网络存储API问世以来,它不再是客户端存储所推荐的方法

Support

在所有主要浏览器基本都支持

Local Storage

Local StorageWeb Storage API中的一种,是一种将键值数据存储在浏览器中的API。它通过提供一个更加直观和安全API来存储简单的数据在浏览器内,解决了Cookies中的问题。

尽管技术上我们只能将字符串存储在本地存储,但这可以存储字符串化的JSON。跟Cookies比,这使我们能将更复杂的数据存储在本地。

Local Storage实现基本的CRUD

我们可以创建、读取、更新和删除cookie使用以下语法:

// 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 的优点

  • 提供了一个更简单直观的界面来存储数据(跟cookie比)
  • 本地存储更安全(跟cookie比)
  • 允许存储更多的数据(跟cookie比)

Local Storage 的缺点

  • 只允许存储字符串

Support

[译]本地存储的概述_第1张图片
img

Session Storage

Session Storage是第二种类型的网络存储API。和Local Storage很相似,不同之处在于 Local Storage 里面存储的数据没有过期时间设置,而存储在 Session Storage 里面的数据在页面会话结束时会被清除。

Session Storage实现基本的CRUD

我们可以创建、读取、更新和删除cookie使用以下语法:

// 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');  

Session Storage优缺点以及Support

Local Storage一样

IndexedDB

IndexedDB是一个对浏览器存储数据来说更加复杂但更加全面的解决方案。IndexedDB 是“一个为了能够在客户端存储可观数量的结构化数据,并且在这些数据上使用索引进行高性能检索的 API”(Mozilla)。这是一个基于javascript、面向对象、数据库使我们方便地存储和检索数据

Ire Aderinokun的文章中,详细的说了如何使用IndexedDB创建一个离线应用程序。

IndexedDB实现基本的CRUD

跟其他浏览器存储方法比起来,使用IndexedDB更为复杂的。在我们可以创建/读取/更新/删除任何数据之前,我们需要首先打开数据库,创建一个放数据的仓库。

function OpenIDB() {  
    return idb.open('SampleDB', 1, function(upgradeDb) {
        const users = upgradeDb.createObjectStore('users', {
            keyPath: 'name'
        });
    });
}

创建(或更新)数据,我们需要经过以下步骤:

// 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的优点

  • 可以处理更复杂的、结构化的数据
  • 在每个“数据库”中,可以有多个“数据库”和“表”
  • 更多的存储空间
  • 控制我们如何与之交互

IndexedDB的缺点

跟其他Web Storage API比起来太过复杂

Support

[译]本地存储的概述_第2张图片
img

WebSQL

自2010年以来,W3C Web应用程序规范工作组已经停止对其维护。它不再是一个HTML规范的一部分,不应使用。

比较

Feature Cookies Local Storage Session Storage IndexedDB
存储空间 ~4KB ~5MB ~5MB Up to half of hard drive
持久数据? Yes Yes No Yes
数据类型 String String String Any structured data
可检索? No No No Yes

原文

你可能感兴趣的:([译]本地存储的概述)