Recently, I used part of the front-end storage in the project. I only had a simple understanding of it before. Today, I will take this opportunity to conduct an in-depth study of front-end storage.

Write in the beginning

Benefits of front-end storage:

  • Facilitate the loading of web pages, avoiding a blank period before sending a request and receiving a response.
  • It is also possible to speed up rendering by reducing requests to servers when real-time up-to-date data is not mandatory.
  • Offline data can still be viewed when the network is poor or absent.

Front-end storage:

First of all, we should clear out the possible storage methods, just open the console and select Application to see.

As we can see, storage is roughly divided into two categories, one is storage class, the other is cache class.

Storage class:
  • Web Storage: THE Storage method proposed in HTML 5 has a capacity of 5 M.

    • localStorage
    • sessionStorage
  • Cookie: A universally supported HTTP-based storage device with a capacity of only 4 KB

  • Database storage:

    • IndexDB
    • Web SQL
The cache class:
  • Cache Storage: it is proposed in the specification of Service Worker that it is generally used with Service Worker for offline Cache.
  • Application Cache: A caching method introduced in HTML5.1 that can be used to build offline applications.

introduce

Cookie, the smaller elder brother

HTTP Cookie, which was originally intended for clients to store session information, requires the server to Set a set-cookie HTTP header for HTTP requests as part of the response, which will contain session information. The browser stores the drawing information in a Cookie and sends the Cookie along with the request.

The composition of the Cookie

Let’s go to Github and check it out on the console

  • The name of the
  • value
  • The domain
  • The path
  • Expiry Time (GMT)
  • The size of the
  • Whether it is an HTTP request
  • security

Domain path expiration times and security are both instructions from the server to the browser. They are not sent to the server as requested, only name and value pairs are sent to the server.

Limitations of cookies

  • If you set a Cookie expiration time, the Cookie automatically becomes invalid when it expires.
  • If no expiration time is set, the Cookie is session-level and disappears automatically when the browser closes.

Advantages and disadvantages of Cookies

Advantages:

1. The expiration time can be controlled. It will not be permanent and has certain security. 2. Can be extended and shared across domains. 3. Encryption and secure Transmission technology (SSL) can reduce the possibility of Cookie cracking. 4. High compatibility.Copy the code

Disadvantages:

1. There are certain quantity and length limits. The length of each Cookie cannot exceed 4 KB; otherwise, the excess part will be truncated. 2. The data in the request header is vulnerable to interception and attack.Copy the code

New power Web Storage

LocalStorage and SessionStorage

We can take a look at its compatibility first, many browsers already fully support it:

Data source: MDN

A reason for

  • Overcome some of the limitations of cookies while storing some data that needs to be strictly controlled on the client side and does not need to be sent to the server.
  • Provides an alternative way to store sessions in addition to cookies.
  • Provides a large storage space to store data across calls.

How to view

They are available as properties of the Window object, and can be accessed directly through window.localStorage and window.sessionStorage.

At the same time, we observe that Web Storage can only store strings. If you use Web Storage to store objects, there will be [Object Object]. We can use json.stringify and json.parse to solve this problem.

Web Storage instance method

  • Clear: Deletes all values
  • GetItem (name): Gets the value based on the key passed in.
  • Key (index): name of the key that obtains the corresponding index.
  • RemoveItem (name): Deletes the key-value pair corresponding to the key
  • SetItem (name, value): Sets a value for the specified name.
SessionStorage without feelings
  • Same-origin policy: Different from cookies, sessionStorage has higher access restrictions. Only the domain with sessionStorage configured can access sessionStorage.
  • Single TAB: Two tabs in the same domain cannot communicate with each other.
  • The previously written sessionStorage cannot be accessed under either a closed TAB ora new TAB
  • Refresh TAB can still access sessionStorage

Scenarios used:

1. Stores session-level small data. 2. Store some information that needs to be stored after the current page refresh, but does not need to be left after closing. 3. It is suitable for single-page applications and can be used to store login status information.Copy the code

Never abandon localStorage

  • Same-origin policy: Same as sessionStorage, access to the same localStorage page must be from the same domain name, same protocol, and same port.
  • After localStorage is set, refresh or re-open the TAB page. Close the browser and re-open the original TAB page.

Scenarios used:

1. Store client data persistently, which can only be deleted by JavaScript or cleared by the user. 2. If there is some slightly large amount of data, such as automatic saving of the editor, etc. 3. Access common data across multiple pages. SessionStorage can only be used for one TAB page, while localStorage can be shared between multiple tabs.Copy the code

SessionStorage and localStorage

  • Life cycle: localStorage is a localStorage. It has no expiration date and can only be deleted by users themselves. SessionStroage is session storage, data is lost when the page is closed.
  • SessionStorage has a single-tab limit, but localStorage does not.

Storage events

Any operation we perform on the Storage object will trigger a Storage event on the document. The event object for this event has the following properties:

  • Domain: domain name of the changed storage space.
  • Key: indicates the name of the key to be set or deleted
  • NewValue: if it is a set value, it is a newValue. Null if it is a delete key.
  • OldValue: The value before the key was changed.

Database level: IndexDB and Web SQL

Web SQL is similar to relational databases in that it uses SQL statements to perform related operations.

IndexDB is similar to NoSQL in that it directly uses JS methods to manipulate data.

Features:

  • Access: Like Web SQL and Web Storage, indexDB can only be accessed under the domain name of the database.
  • Storage time: The storage time is permanent, unless the user clears the data, it can be used for long-term storage.
  • Size limits: There are no mandatory limits. However, indexDB will pop up a box in the browser for you to confirm when data exceeds 50 megabytes.
  • Performance: indexDB queries are relatively slow, while Web SQL is relatively fast.

The actual operation

The first step is to open the database

var request = indexedDB.open(name, version);
Copy the code

The first parameter is the name of the database and the second parameter is the version number of the database.

The second step is to add data

Create transaction and add data read and write permissions.

var transaction = db.transaction(storeName, 'readwrite');
Copy the code

Get the objectStore and call the Add method to add data

var store = transaction.objectStore(storeName);
var request = store.get(key);
request.onsuccess = function (e) {
    data = e.target.result;
    console.log(student.name);  
};
Copy the code

Step 3 Delete the data

Deletion also requires the creation of a transaction, which calls the delete interface and deletes objects through the key.

var transaction = db.transaction(storeName, 'readwrite');
var store = transaction.objectStore(storeName);

store.delete(key);
Copy the code

Step 4: Find the data

  • According to the key to find

    Start the transaction, get objectStore, and call get() to get the object.

    var transaction = db.transaction(storeName, 'readwrite');
    var store = transaction.objectStore(storeName);
    var request = store.get(key);
    request.onsuccess = function (e) {
        data = e.target.result;
        console.log(student.name)
    };
    Copy the code
  • Use index lookup

    The createIndex method is used to create the index. The method takes three parameters: the name of the index, the name of the index attribute field, and whether the index attribute value is unique.

    objectStore.createIndex('name'.'name', {
        unique: false
    })
    Copy the code

    With the index created, we can use the index to query:

    var transaction = db.transaction(storeName);
    var store = transaction.objectStore(storeName);
    var index = store.index(search_index);
    index.get(value).onsuccess = function (e) {
        data = e.target.result;
        console.log(student.id);
    }
    Copy the code
  • The cursor traverses the data

    var transaction = db.transaction(storeName);
    var store = transaction.objectStore(storeName);
    var request = store.openCursor(); // Successfully open the cursor
    var dataList = new Array(a);var i = 0;
    request.onsuccess = function (e) {
        var  cursor = e.target.result;
        if (cursor) {
            console.log(cursor.key);
            dataList[i] = cursor.value;
            console.log(dataList[i].name);
            i++;
            cursor.continue();
        }
        data = dataList;
    }
    Copy the code

Step 5, update the object

To update an object, we first take it out, modify it, and then put it back in.

var transaction = db.transaction(storeName, 'readwrite');
var store = transaction.objectStore(storeName);
var request = store.get(key);
request.onsuccess = function (e) {
    var data = e.target.result;
    for (a in newData) {
        data.a = newData.a;
    }
    store.put(data);
}
Copy the code

Step 6: Close and delete

To close the database, call the close method of the database

db.close();
Copy the code

Delete a database using the database object deleteDatabase method

function deleteDB (name) {
    indexedDB.deleteDatabase(name);
}
Copy the code

IndexDB characteristics

  • Its data is stored in object storage space.
  • To create an object storage space, first define a key and then add data.
  • You can use a cursor query.

IndexDB compatibility remains a major issue, and Web SQL, while outdated, is still very compatible and almost universally available on mobile.

Cache Storage

Cache Storage is used to store Response objects, that is, to Cache HTTP responses. A Cache Storage is a collection of multiple caches. Each Cache can store multiple response objects. It’s based on Promise. I will not go into details here.

Application Cache

It is a new application coarsening technology introduced in HTML5, and its emergence means that Web applications can be cached, run without a network, and build offline applications.

Advantages:

  • Offline browsing
  • Improved page loading speed
  • Reduce server stress

Generally, Application Cache is only used to store static resources. There are two main steps to use Application Cache:

1. The server maintains a manifest

2. Set a parameter on the browser.

<html manifest="demo">
Copy the code

In general, we must set the correct MIME-type to “text/cache-manifest” for the manifest file, which needs to be configured on the server side.

In Progressive Web Application, Application Cache and Service Worker undertake major tasks.

reference

MDN: LocalStorage , sessionStorage, indexDB

Local storage vs. offline storage

IndexDB for front-end storage