Several storage provided by the browser

With the development and evolution of mobile networks, we are now on the phone in addition to native APP, can run WebApp, it means that the use, run out and go. A good WebApp and can even have a native App comparable features and experiences. WebApp excellent performance, in part because thanks to enhance the browser storage technology. Cookie function of storing data have been difficult to meet the required development, and gradually substituted WebStorage IndexedDB.

Cookie

What is a Cookie

Cookie refers to certain websites in order to identify the user identity and data stored on the user's local terminal (usually encrypted). Cookie is generated by the server, client maintenance and storage. By Cookie, you can let the server know the source from which the request is the client and the client state maintenance. For example, after logging refresh and jump, the request header will carry the set-cookie attribute when landing in Response Header, Web server when it receives a request to read the value of the Cookie, Cookie is based on the value can be judged and recovery Some users of the information state.

Through the above description we can know, Cookie's job is not stored locally, but the state is maintained. Because HTTP is a stateless protocol, the communication state is not saved between requests and responses. This means that, in this stateless server interaction, the user will not know what to do once, also hindered the realization of interactive Web applications. HTTP Cookie is to circumvent the stateless and the birth of a solution, the server can maintain the status of the user and the server session by setting and reading the user information Cookie contains. Cookie can be understood as a small size in the browser is stored text file, at the time of carrying the requested user information Cookie attached to the HTTP request, the server can obtain the status of the client.

Typical application scenarios Cookie has automatic login (remember password), shopping cart functionality, record user behavior (do goods / advertising recommended) and so on.

Cookie principles and generate ways

As a simple example, in a typical online shopping scenario, a user browse a few pages, I bought a box of biscuits and bottles of beverages, the final checkout, because of the stateless nature of HTTP, the server can not know in the end user to buy What, or users and can not be purchased on the correspondence. With Cookie and after, when the user successfully logs in, the server returns a successful login response time will be returned to the client a Cookie carry user information, the client will save the Cookie. When users buy a commodity and sends a request, the request will take this Cookie, Cookie and the server can check the Cookie and obtain user information, allowing users to purchase goods and can be obtained corresponding to the.

First visit the site, the browser makes a request, the server responds to the request, adds a set-cookie option in response to head inside, put the Cookie response to the request, the browser requesting a second time, would otherwise, Cookie expiration time, domain, path, valid for the site can be specified by the Cookie Cookie request header information sent to the server, the server can identify the user's identity, as required.

Cookie is generated mainly in the following two ways:

1.http response header中的set-cookie。

2.js by document.cookie read and write cookie, cookie can be resolved in the form of key-value pairs show.

Cookie defects

1.Cookie not big enough. Cookie size limit is about 4KB, for complex storage requirements is not enough. When Cookie more than 4KB when it will face the fate of being cut. It would appear, Cookie can only be used to access a small amount of information, and even some browsers for a number of sites do have restrictions Cookie. Here we must note that, 4KB capacity limitation here is the Cookie name = value is the value of a domain name under all of the Cookie is not shared.

2. Excessive Cookie will bring significant performance / resource waste. Cookie is followed by the domain name, carrying Cookie with all requests in a domain name. In fact, a lot of scenes does not require authentication, such as requesting a picture or CSS file, this time carrying Cookie also resulted in a waste of performance / resources. There is a solution is to use CDN services as a way to request a static resource files, because the domain name and domain name of the master CDN is separate, there would be a Cookie comes in the request.

Cookie Security

Although some of the properties may Cookie appropriate to maintain security, but it is still unsafe sex is almost inherent.

To compensate for the limitations of Cookie, WebStorage arises. WebStorage is new in HTML5 local storage solutions, including the SessionStorage and LocalStorage categories. Once you have WebStorage, Cookie will be able to feel at ease only as a client and channel server interaction (maintaining client state), and do not have to worry about storing things.

LocalStorage

LocalStorage is one of WebStorage.

LocalStorage features

1. Save data exist for a long time next visit the website, read pages previously saved data directly.

2. The size of the storage limit is about 5MB.

3. Only use the client does not communicate with the server.

4. The interface package good agreement.

Based on the above characteristics, LocalStorage can be used as a local cache of the browser program, to enhance the screen's first page rendering speed (return according to the first request, some of the same information directly stored locally).

LocalStorage stored / read data

LocalStorage saved data is in the form of key-value pairs, that is, every piece of data has a key name and the corresponding value, and all data is saved in text format.

Data is stored using the setItem () method. This method takes two parameters, a first name is a bond, the second data is stored.

localStorage.setItem(key, value);

Reading data using the getItem () method. This method takes one parameter, the key name.

localStorage.getItem(key);

Look at a complete example:

function testLocalStorage() {
    if (window.localStorage) {
        localStorage.setItem('name', 'yanggb');
        console.log(localStorage.getItem('name'));
    }
}

LocalStorage usage scenarios

LocalStorage in memory and almost no special restrictions, in theory, some of the Cookie incompetence, storage simple key-value pair storage tasks can be handed over LocalStorage do.

One of the features considered to LocalStorage are persistent, so sometimes we tend to use it to store some content stable resources. For example, the picture content-rich electronic business site can use to store pictures LocalStorage string Base64 format.

SessionStorage

SessionStorage saved data for a browser session, when the session ends (usually the window is closed), the data will be cleared. SessionStorage special thing is that even two pages under the same domain name, as long as they are not open in the same browser window, so their contents can not SessionStorage sharing, and shared among all homologous LocalStorage window, Cookie also in All share homology in the window. In addition to the shelf life of different lengths, SessionStorage properties and methods and LocalStorage exactly the same.

SessionStorage features

1. The session-level browser stores.

2. The memory size is limited to about 5MB.

3. Only use the client does not communicate with the server.

4. The interface package good agreement.

Based on the above characteristics, SessionStorage can effectively forms cache information, when such information is a form of refresh will not be lost.

SessionStorage usage scenarios

SessionStorage more suitable for storage lifecycle session-level information and its synchronization, this information applies only to the current session. When you open a new session, it also requires a corresponding update or release. Such as micro-blog using the browser memory footprint SessionStorage a single session, it will save a lasturl key to the corresponding url address your last visit. When you switch the url, the key will be updated; when you close the page when the key will be released. Such processed data SessionStorage appropriate.

The difference between SessionStorage, LocalStorage and Cookie

SessionStorage, LocalStorage and Cookie are stored in the browser, follow the browser's same-origin policy, different places distinguished by their life cycle and scope.

Different scopes

LocalStorage as long as the same agreement, the same host name, the same port can read / modify a LocalStorage to the same data. And to be more stringent than the SessionStorage LocalStorage that, in addition to the protocol, host name, port, also asked in the same window (that is, the browser tab) the next.

Different life cycle

LocalStorage is persistent local storage, data stored in them are never out of date, the only way to make it disappear is to manually remove; and SessionStorage temporary local storage, session level of storage, when the session ends (page is closed), the stored content will also be released.

Web Storage is a definition to use are very simple things. It uses key-value pairs are stored, this model is somewhat similar to the object, but the key can only store strings. If you want to get the object, you need to first resolve the string round. Therefore, Web Storage can be seen to expand Cookie, can only be used to store small amounts of data simple. When confronted with large-scale, complex data structures, we need to use IndexedDB.

IndexedDB

IndexedDB是一种低级的API,使用索引来实现对其间存储数据的高性能搜索,用于客户端需要存储大量结构化数据(包括文件和blobs)的场景。

IndexedDB可以看作是一个运行在浏览器上的非关系型数据库。既然是数据库了,那就不是5M、10M这样小打小闹的级别了,理论上来说,IndexedDB是没有存储上限的,一般来说不会小于250M。另外,它不仅可以存储字符串,还可以存储二进制数据。

IndexedDB的特点

1.键值对存储。IndexedDB内部采用对象仓库(Object Store)存放数据,所有类型的数据都可以直接存入,包括JavaScript对象。在对象仓库中,数据以键值对的形式保存,每一个数据记录都有对应的主键,且主键是唯一的,不可重复,否则会抛出错误。

2.异步。IndexedDB在操作时不会锁死浏览器(异步线程,不会挂起其他线程),用户依然可以可以进行其他操作。这与LocalStorage形成对比,后者的操作是同步的(会挂起其他线程)。异步设计是为了防止读写大量数据的时候拖慢网页的表现性能。

3.支持事务。IndexedDB是支持事务(Transaction)的,也同样支持事务的ACID特性。这意味着在一系列的操作步骤中,只要有一步失败,整个事务就会取消,数据库将回滚到事务发生之前的状态,不存在只改写一部分数据的情况,保证数据的完整性和一致性。

4.同源限制。IndexedDB受浏览器同源策略的限制,每一个数据库都严格对应创建它的域名。网页只能访问自身域名下面的数据库,而不能访问跨域的数据库。

5.存储空间大。IndexedDB的存储空间比LocalStorage大得多,一般来说不小于250MB,甚至没有上限。

6.支持二进制存储。IndexedDB不仅可以存储字符串,还可以存储二进制数据(ArrayBuffer对象和Blob对象)。

IndexedDB的创建、关闭和删除操作

在IndexedDB的大部分操作并不是我们常用的调用方法(返回结果的模式),而是请求-响应的模式。

1.建立打开IndexedDB。

window.indexedDB.open("testdb");

上面这条语句并不会返回一个DB对象的句柄,我们得到的是一个IDBOpenDBRequest对象,在这个对象中的result属性中会包含我们想要的DB对象。

除了result之外,IDBOpenDBRequest接口还定义了几个重要的属性。

属性
onerror 请求失败的回调函数句柄
onsuccess 请求成功的回调函数句柄
onupgradeneeded 请求数据库版本变化句柄

来看一个完整的例子:

// 全局myDB对象
var myDB = {
    name: 'testdb',
    db: null
}

// 定义创建打开indexedDB的函数
function openDB (dbName) {
    var request = window.indexedDB.open(dbName);
    // 创建打开失败事件
    request.onerror = function(e) {
        console.log('open indexdb error');
    }
    // 创建打开成功事件
    request.onsuccess = function(e) {
        myDB.db = e.target.result;
        console.log(myDB.db);
    }
}

// 调用创建打开函数
openDB(myDB.name);

2.关闭IndexedDB。

// 定义关闭IndexedDB函数
function closeDB() {
    myDB.db.close();
}

这里要注意调用close()方法的是IndexedDB对象,且关闭并不会删除浏览器中的IndexedDB数据库。

3.删除IndexedDB。

// 定义删除IndexedDB的函数
function deleteDB() {
    window.indexedDB.deleteDatabase(myDB.name);
}

要特别提及的是,IndexedDB的命名是严格区分大小写的,无论是创建还是删除都要注意这一点。

关于IndexedDB的使用,内容比较多,另外开篇去深入了解。

Cookie、WebStorage和IndexedDB之间的区别

从上表中可以看出,Cookie已经不建议用于存储用途。如果没有大量数据存储需求的话,可以使用LocalStorage和SessionStorage。对于不怎么改变的数据尽量使用LocalStorage做存储,否则可以用SessionStorage做存储。

浏览器存储的总结

因为浏览器存储和缓存技术的出现和发展,前端应用带来了无限的可能。近年来,基于存储、缓存技术的第三方库层出不穷,此外还衍生出了PWA这样优秀的Web应用模型。

1.Cookie的本质工作并不是本地存储,而是状态维持。

2.WebStorage是HTML5专门为浏览器存储而提供的数据存储机制,不与服务端发生通信。

3.IndexedDB用于客户端存储大量结构化的数据。

 

"你一边讨厌着你现在的生活状态,一边懒散地混过每一天。"

Guess you like

Origin www.cnblogs.com/yanggb/p/10675855.html