18
Please indicate the source for reprinting: Grape City official website, Grape City provides developers with professional development tools, solutions and services, and empowers developers.

Data persistence

Data persistence refers to the process of transforming the data model in memory into a storage model, and the process of transforming the storage model into a data model in memory. Under normal circumstances, the data we store will remain until we delete the relevant content; or the data will be saved until the end of the browser session and the user closes it.
But in reality it will be more complicated. Users, operating systems, browsers or plug-ins can block or delete persistent data at any time. The browser has the right to delete the stored content of relatively old or relatively large project content; it can also record the page status. When we leave the current page and reopen the page, the last recorded content will be saved and can be used directly.

scenes to be used

When the data does not need to be sent to the web server or the data content is not needed, you only need to store and manipulate the data in the browser (also called the client). Data persistence will be used, and the specific data needs to be stored and manipulated in the browser. Including the following situations:

  • Preserve the state of the client application—such as the current screen, entered data, user preferences, etc.
  • Utilities that access local data or files and have strict privacy requirements
  • Progressive web application (PWA) that works offline
    Next, I will compare the different client storage methods in 10 in detail, including the limitations, advantages and disadvantages of these methods, and the use of each method, so that you can choose according to your own usage scenarios.
  • JavaScript variables
  • DOM node (DOM node) storage
  • Web storage (localStorage and sessionStorage)
  • IndexedDB/index data-
  • Cache API (Do not use AppCache)
  • File system access API
  • File and directory item API
  • cookies
  • window.name
  • WebSQL

    Overall comparison

1.1.png

The text will compare these ten methods from the three perspectives of capacity, read and write speed, and data durability. Next, I will introduce the details for you.

  1. JavaScript variables
    Storing the state in a JavaScript variable is the fastest and easiest, an example is as follows:

2.png

advantage

  • Easy to use
  • Quick
  • No need to serialize or deserialize
    Disadvantages
  • Volatile: Refreshing or closing the tab will clear everything
  • Third-party scripts can check or override global (window) values
    If you are already using JS variables, you can consider storing the variable state permanently when page unloads

2. DOM node (DOM node) storage

3.png

Most DOM elements, whether on the page or in memory, can store values in named attributes. It is safer to use attribute names prefixed with data-:

  • This attribute will not be associated with HTML
  • Values can be accessed through dataset attributes instead of the longer .setAttribute and .getAttribute methods and stored as strings, so serialization and deserialization may be required. E.g:

4.png

Advantage

  • The value can be defined in JavaScript or HTML, such as <main data-value1="1">
  • Used to store the state of a specific component
  • DOM is too fast
    Disadvantages
  • Fragile: refreshing or closing the current content will clear all content (unless the server passes the value into the HTML)
  • Strings need to be serialized and deserialized
  • Larger DOM will affect performance
  • Third-party scripts can check or override values
    DOM node storage is slower than variables. When storing the state of the component in HTML is feasible, you need to pay attention to this when using it. Now this method has been gradually eliminated, because the storage speed of the DOM node spanning tree is too slow, and the efficiency in large projects is very low. But in order to solve this problem, HTML 5 Canvas now has a detailed solution. For example, SpreadJS pure front-end table component has introduced Canvas drawing model and double cache canvas technology, which greatly improves the project efficiency.

3. Web storage (localStorage and sessionStorage)

5.png

Web storage provides two similar APIs to define name/value pairs:

  • window.localStorage: store persistent data
    •- window.sessionStorage: keep only the session data while the browser option content remains open

Use the .setItem method to store or update the named item:

6.png
Use the .getItem method to retrieve:

7.png
Use the .removeItem method to delete:

8.png

Advantage

  • Simple name/value pair API
  • There are session and persistent storage options
  • Good browser support
    Disadvantages
  • String only: serialization and deserialization required
  • Unstructured data without transactions, indexes, or searches
  • Synchronous access will affect the performance of large data sets

Web storage is very suitable for simpler, smaller, and special values. It is not practical to store large amounts of structured information, but we can avoid performance problems by writing data when the page is unloaded.

4.IndexedDB/indexed database

10.png

IndexedDB provides a low-level API similar to NoSQL to store large amounts of data. You can perform index storage, use transactions to update storage, and use asynchronous methods to search storage.
IndexedDBapi is complex and requires some event handling. The following functions open the database connection when passing the name, version number, and optional upgrade function (called when the version number changes):

11.png

The following content connects to the myDB database and initializes todo object storage (similar to SQL tables or MongoDB collections). Then define an auto-increment key named id:

12.png

After the database connection is ready, you can add new data items in the transaction:

13.png

The value can be retrieved at this time

14.png

Advantage

  • Flexible data storage with maximum space
  • Powerful transaction, index and search options
  • Good browser support
    Disadvantages
  • Complex callbacks, API based on events
  • IndexedDB can store large amounts of data, but requires the use of wrapper libraries such as idb, Dexie.js or JsStore.
  1. Cache API

15.png

The Cache API provides storage for HTTP request and response object pairs. You can create any number of named caches to store any number of network data items.

APIs usually respond to the web for caching progressive web applications. When the device is disconnected from the network, the cached content is re-provided so that the web application can run offline.

The following code stores the network response in a cache named myCache:

16.png

Similar functions can retrieve items from the cache. In the following example, it returns the response body text:

17.png

Advantage

  • Store any network response
  • Can improve web application performance
  • Allow web applications to run offline
  • Modern API based on Promise
    Disadvantages
  • Not suitable for storing application state
  • Not very useful outside of progressive web applications
  • Apple is not friendly to PWAs and Cache API

Cache API is the best choice for storing files and data retrieved from the network. We can use it to store application state.

  1. File system access API

18.png

The file system access API allows the browser to read, write, modify, and delete files from the local file system. The browser runs in a sandbox environment, so users must grant permissions to specific files or directories. This will return a FileSystemHandle so that the web application can read or write data like a desktop application.

The following function saves the blob to a local file:

19.png

Advantage

  • The web application can safely read and write local files
  • No need to upload files or process data on the server
    Disadvantages
  • Only minimal browser support (Chrome only)
  • API will change

The advantages of this storage method are almost overwhelming

  1. File and directory item API

20.png

The file and directory entry API provides a file system that can be used in the domain, which can create, write, read, and delete directories and files.
Advantage

  • There are some interesting uses to explore
    Disadvantages
  • Non-standard and incompatibility between implementation and behavior may change

However, at present, MDN clearly states: Do not use this option on production sites, and it will take several years for extensive technical support.

  1. cookies

21.png

Cookies are domain-specific data used to track users, but they are essential for any system that needs to maintain the state of the server (such as logging in). Unlike other storage mechanisms, cookies are (usually) passed on HTTP requests and responses between the browser and the server. Both devices can check, modify and delete cookie data.
Use document.cookie to set the cookie value in the client. How to use:

22.png

The value cannot contain commas, semicolons or spaces, so the encodeURIComponent method is required:

23.png

Example: Set a status cookie, which will expire in 10 minutes and be available on any path in the current domain:

24.png

document.cookie returns a string containing each name and value pair separated by semicolons. E.g:

25.png

The following function parses a string and converts it into an object containing name-value. E.g:

26.png

advantage

  • Data state can be maintained between client and server
  • Limited to domain and path (optional)
  • Automatic expiration control, maximum expiration time (seconds) or expiration time (date)
  • Used in the current session by default (set the expiration date, you can keep the data after the page is refreshed and the tab is closed)
    Disadvantages
  • Browsers and plugins block cookies (they are usually converted into session cookies so that the site can continue to work)
  • JavaScript implementation needs to create your own cookie handler or choose a library such as js cookie
  • Strings need to be serialized and deserialized
  • Limited storage space
  • Unless access is restricted, third-party scripts can check cookies
  • Invasion of privacy
  • Each HTTP request and response will append cookie data, which affects performance (store 50Kb of cookie data, and then request 10 1-byte files, which will generate 1 megabyte of bandwidth)

Too many shortcomings, not necessary, cookie is not recommended

  1. window.name

27.png

window.name sets and obtains the name of the window browsing context. We can set a string value that remains the same between browser refresh or linking to another location and clicking "Back". E.g:

28.png

Check the content:

29.png

Advantage

  • Easy to use
  • Can only be used for session data
    Disadvantages
  • Strings need to be serialized and deserialized
  • Pages in other domains can be read, modified or deleted

Window.name was not originally designed as a method of data storage, but can be used as a black technology.

  1. WebSQL

30.png

WebSQL is a method of introducing SQL database storage into the browser. Sample code:

31.png

Advantage

  • More suitable for robust client data storage and access
  • Server side uses SQL syntax
    Disadvantages
  • Browser support is limited
  • Inconsistent SQL syntax across browsers
  • Asynchronous callback API is not flexible enough
  • Poor performance

Can be used in conjunction with the database, but also provides a method for client storage.

to sum up

This article introduces 10 different client-side storage solutions in detail. What you can see is that no one is perfect. In order to solve different situations in complex web applications, we need to learn more APIs. According to different situations and local conditions, flexible use will solve the problem more efficiently.


葡萄城技术团队
2.7k 声望28.5k 粉丝

葡萄城创建于1980年,是专业的软件开发技术和低代码平台提供商。以“赋能开发者”为使命,葡萄城致力于通过各类软件开发工具和服务,创新开发模式,提升开发效率,推动软件产业发展,为“数字中国”建设提速。