sessionStorage, localStorage, cookie and indexDB applications

sessionStorage与localStorage

basic information

  • sessionStorage is used to temporarily save the data of the same window (or tab), which will be deleted after closing the window or tab.
  • localStorage is used for permanent storage of data, and pages of the same origin (same protocol, domain name, and port) can be accessed in different tabs.
  • Storage space: the storage space of sessionStorage and localStorage is 5M, and the storage content can only be a string
  • Scope: The scope of sessionStorage is that pages of the same origin can be accessed on the same tab page, and localStorage can also be accessed on different tab pages

How to use

It should be pointed out by everyone, directly on the code

let key = 'mykey';
// 只能存字符串
sessionStorage.setItem(key, JSON.stringify({
    
    a:1}));
let value = sessionStorage.getItem(key);
// 取出来的别忘了转换格式
value = JSON.parse(value);
// 反复存储
sessionStorage.setItem(key, 1);
value = sessionStorage.getItem(key);
// 就算是存数字也是会被存成字符串
value = Number(value);
// localStorage使用方式跟sessionStorage相同
localStorage.setItem(key, 1);
value = localStorage.setItem(key);

// 删除所有保存的数据
sessionStorage.clear();
localStorage.clear();

scenes to be used

Because both sessionStorage and localStorage can keep the data from being cleared when the page is jumped or refreshed, they can be used in the following scenarios

  1. Used for data transfer between pages, such as jumping from page A to page B when there are multiple pages
  2. Speed ​​up the page rendering speed, the data is stored in the storage, and when the page is refreshed, the interface is not adjusted to directly fetch the data from the storage
  3. localSotrage can save the state of entering the page for the first time, such as some basic information. When entering the page next time, it will first display the locally stored information, and then call the interface to refresh the page, which can reduce the waiting time of the user
  4. Because sessionStorage clears data when the page is closed, it can be used to save some sensitive data (such as account information), localStorage is permanently saved, so sensitive information cannot be saved
  5. Some operations, such as base64 pictures, can also be saved, but it is easy to burst the memory, so the content with too much memory should not be saved in the storage

cookie

Basic Information

  • Cookie is also a user cache, it is mainly used to store some important information
  • The size of the cookie is 4kb
  • The cookie will be sent to the server every time it is requested, so it will affect the request speed
  • The existence time of cookies can be set, and those that do not need to be stored for a long time must be deleted in time
  • Cookies can also be set on the server side, mainly used to pass some fixed parameters and token in the past (token is used for current page session authentication)
  • When the cookie is not safe, it is used to save the token. Here only the storage function of the cookie is discussed.

How to use

// 直接拿到字符串
let cookie = document.cookie;
// cookie的内容是这样的 "a=1;b=2;c=3"
// 简单的示例获取a
let a = cookie.split(';')[0].spilt('=')[1];
// 赋值
document.cookie = "d=4";
// 执行后cookie="d=4;a=1;b=2;c=3"
// 下面的写法打乱了队形,不要那么写
document.cookie = "4";
// 执行后cookie="4;d=4;a=1;b=2;c=3"
// 删除cookie
document.cookie = "d=''";

scenes to be used

不是场景非常特殊(比如很老的项目,已经用了)别用它,影响性能,存储空间小

indexDB

Basic Information

  • IndexedDB is a low-level API for storing large amounts of structured data (also files/binary large objects (blobs)) on the client side
  • The main feature of IndexedDB is its large storage space, which solves the problem of insufficient localStorage space. Theoretically, as much as the browser can store, it can probably store as much, and a few gigabytes are small
  • indexDB query is asynchronous, that is, when querying big data, asynchrony will not block the event loop of js

How to use

The use of indexDB is quite complicated, and it cannot be explained clearly in a blog. If you want to do it well, you need to learn the system and package the plug-in yourself in combination with the actual application scenario. Here I will only introduce the idea of ​​​​use

  • Encapsulate the basic method of adding, deleting, modifying and checking. For simpler ones, you can use third-party plug-ins (there are maps below)
  • indexDB needs a special table to store version information and user information. At the same time, there must be a special table on the server (a json file is also acceptable) to store this information. Before using indexDB, you must first adjust a very fast interface to Confirm whether the current data is to use the server or the local
  • It is necessary to handle the logic of asynchronous operations. Because indexDB is asynchronous, you need to ensure the timing of indexDB queries and server queries. For example, if you want to quickly display indexDB data first, and then call remote data to refresh local data, if the interface is fast enough , the data may be requested earlier than indexDB, then there will be a problem with the timing
  • It is necessary to consider the situation when the client clears the cache and enters the page for the first time
  • Pay attention to which data should be deleted when you leave the interface (sessionStorage space is not enough), and clear it in time
    Basic usage method Here is an example of MDN,
// 我们的客户数据看起来像这样。
const customerData = [
  {
    
     ssn: "444-44-4444", name: "Bill", age: 35, email: "[email protected]" },
  {
    
     ssn: "555-55-5555", name: "Donna", age: 32, email: "[email protected]" }
];
const dbName = "the_name";

var request = indexedDB.open(dbName, 2);

request.onerror = function(event) {
    
    
  // 错误处理
};
request.onupgradeneeded = function(event) {
    
    
  var db = event.target.result;

  // 建立一个对象仓库来存储我们客户的相关信息,我们选择 ssn 作为键路径(key path)
  // 因为 ssn 可以保证是不重复的
  var objectStore = db.createObjectStore("customers", {
    
     keyPath: "ssn" });

  // 建立一个索引来通过姓名来搜索客户。名字可能会重复,所以我们不能使用 unique 索引
  objectStore.createIndex("name", "name", {
    
     unique: false });

  // 使用邮箱建立索引,我们向确保客户的邮箱不会重复,所以我们使用 unique 索引
  objectStore.createIndex("email", "email", {
    
     unique: true });

  // 使用事务的 oncomplete 事件确保在插入数据前对象仓库已经创建完毕
  objectStore.transaction.oncomplete = function(event) {
    
    
    // 将数据保存到新创建的对象仓库
    var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers");
    customerData.forEach(function(customer) {
    
    
      customerObjectStore.add(customer);
    });
  };
};

Those who want to do in-depth research are recommended to look directly at the MDN address , and it also recommends some useful plug-ins. Or find some books to read (the author has not read any books, so I have no recommendation). The blog author has read a lot, but the quality is not very good. brief introduction
insert image description here

scenes to be used

  • The main premise is that there should be no sensitive data that leaks customer privacy. The amount of data is large enough and localStorage is not enough. If it is not necessary, don’t use a sledgehammer
  • In the gis project, there are a lot of geographic information data to be stored. For example, a static geojson may be 10 megabytes, tens of thousands of data, which can be stored in indexDB for on-demand use, because more than ten megabytes of data are stored in js for repeated use. often crashes the page
  • Visual large-screen projects, many companies do big data visualization, often for internal use, the performance of the server given is poor, the interface is often very slow, a large amount of data can be stored locally, and the speed of the second opening is accelerated. The advantage of localStorage is of course that it saves more, and because it is used internally by the company, basically all information can be stored in it
  • The h5 page in your own app, because the app is owned by your company, and the local data security has been done well, you can safely and boldly store more data locally, which can optimize the performance of the h5 page
  • On a large platform, there are a lot of shared data to be transferred, because the storage is shared with the same domain name, everyone stores things in it, and sometimes the storage space will be blown up, the author has encountered a pig teammate who stored base64 in localStorage, As a result, the author cannot find the data he saved. Because the space of indexDB is large enough, not to mention base64, binary can be stored, just disk it
  • Because it is asynchronous, use it to avoid blocking when querying large amounts of data. For example, if you get 100,000 pieces of data (already used in some places), you need to take a specific piece of data at this time. If you use js to filter synchronously, the calculation will definitely block the main event loop, and you can also adjust the backend interface, but Web Worker, indexDB can also be used as a solution, and it is also a good choice when you have no better solution

Regarding indexDB, the author is also discovering a lot of things, so I will write so much, and I will add when I think of it.

Summarize

sessionStorage, localStorage, and indexDB are all user caches, shared with pages of the same origin. The main purpose is to improve performance and pass parameters. The difference lies in the amount of data, scope, and life cycle.
My personal suggestion is that if the server performance is excellent, try not to store too much data on the client. You cannot guarantee that the data you store will be insensitive. The more you store, the greater the risk. Use sessionStorage first, then localStorage, and finally indexDB. Cookies can be used or not.

Guess you like

Origin blog.csdn.net/qq_38217940/article/details/125360427