For other translations of this series, see [JS Working Mechanism – Xiaobai’s 1991 column – Nuggets (juejin. Cn)] (juejin.cn/column/6988…

Reading Index: 3 Local storage is not used in many scenarios. However, local storage may be used to cache data for visualization or large data display to improve performance. You can read as you see fit.

An overview of the

Choosing the right storage mechanism is important when designing your application. A good storage engine should ensure data stability, reduce bandwidth, and improve performance. Correct storage cache strategy is one of the core of offline mobile applications. More and more users take it for granted that they can use mobile web applications offline. In this chapter, we’ll discuss storage apis and services, providing the usual guidance to help you make the right choices when building your application.

The data model

The data storage model depends on how the data is organized internally. This affects the overall application design, balancing performance against storage issues. There is no better solution or solution to all problems, it’s up to the developers themselves. So let’s first look at which data models we can choose

  • Structured: Data is stored in a predefined table of fields, just like a typical SQL-like database. They are adaptable and easy to query dynamically. The structured storage in the browser is IndexedDB.
  • Key-value pair: A key-value pair data store, similar to a NoSQL database, that stores and retrieves unstructured data with unique keys. Key-value data storage, similar to a hash table, so that the time taken to access an index is fixed. Good examples of key/value data storage are the browser-side Cache API and server-side Apache Cassandra.
  • Byte stream: This simple model stores data as fixed length, confuses byte variables of strings, and lets the application layer control its internal data organization. This model is especially suitable for file storage and other hierarchical bloB data. Typical examples of byte stream storage include file systems and cloud storage devices.

persistence

The data storage method of web application can be analyzed by the storage time of data:

  • Session persistence: This data is persisted only when a web page’s Session or a browser TAB is activated. An example of a persistent data store is the Session Storage API.
  • Device persistence: This type of data is persisted across sessions and browser tabs by some device vendors. One mechanism for persistent storage on devices is the Cache API.
  • Global persistence: This type of data persistence is cross-session and cross-device. Therefore, this is a stable way to persist data. It can’t be stored on the device itself, so you need some server-side storage.

Persistence of data in the browser

There are now some browser apis that support data storage. Let’s take a look at some and do a simple comparison so you can make your choice.

There are a few things to consider before choosing the right approach. Of course, you need to understand how your application works first, and then maintain and enhance it. Even if you already have the answer, here are some questions to consider:

  • Browser support – Prefer standardized, stable apis because they have been around for a long time and are widely used. These apis also have a rich documentation and community of developers.
  • Transactions – Sometimes it is important to atomize the success or failure of a set of stored operations. Traditionally, databases have been atomized using a transaction model. In the transaction model, the update of related data is divided into arbitrary units.
  • Asynchronous synchronization – Some storage apis are synchronous, which blocks the current thread. So use asynchronous whenever possible.

contrast

Take a look at the apis currently used by Web developers and a simple horizontal comparison

File system API

Using the file system API, web applications can create, read, navigate, and write files in the sandbox of the user’s local file system.

The API is divided into several parts:

  • Read and manipulate files:File/Blob.FileList.FileReader
  • Create and write files:Blob().FileWriter
  • Directory and file access:DirectoryReader.FileEntry/DirectoryEntry.LocalFileSystem

File system apis are nonstandard apis. You can’t use it in distributed applications because it doesn’t work for all users. Implementations are incompatible, and apis may change.

File and directory API file systems are used to represent a file system. These objects can be retrieved from the filesystem property of any filesystem entry. A few browsers provide additional apis to create and manipulate file systems.

This interface does not allow developers to access the user’s file system. Instead, developers get a virtual disk in the browser sandbox. To access a user’s file system, install the Chrome plug-in.

Request a file system

A web application can access the sandbox file system by calling window.requestFilesystem () : if you call requestFileSystem() for the first time, a new storage is created for your application. Keep in mind that the file system is a sandbox and your application cannot access other application files.

After accessing the file system, you can perform most of the standard behavior on files and directories.

File systems are a different storage approach than others, designed to meet scenarios where client storage cannot. Typically, they are used to process large binary blobs files or to share data in programs outside of the browser context.

The following is a good example of using FileSystem:

  • Persistent upload – Select a file or directory to upload, first copy the file to the local sandbox, then upload one shard at a time
  • Video games, music or other apps with lots of media resources
  • Offline media/image editor or cache accelerated – blocks of data are large and require reading and writing
  • Offline media player – it requires downloading large files for later playback or quick track-finding – buffering
  • Offline webmail client – Download attachments and store them locally

Take a look at the browser support:

The local store

The localStorage API allows you to access the Storage object of the document source. The store is cross-browser session. LocalStorage is very similar to sessionStorage except that data stored in localStorage has no expiration date and is cleaned up once the page is closed.

Both localStorage and sessionStorage store their data only in a specific page source, the so-called page source contains protocol, host name and port. Take a look at browser support

The Session storage

The sessionStorage property allows you to get the sessionStorage object for the current source. SessionStorage is similar to localStorage. The difference is that data stored in localStorage has no expiration time, whereas data in sessionStorage is lost when the page session ends. The duration of a page session is when the browser opens and when the page reloads and resumes. Opening a new page or window in a new TAB causes a new session to be reinitiated, which doesn’t work the same way session cookies do.

Similarly, both localStorage and sessionStorage store their data only in a specific page source

Take a look at browser support

Cookies

A cookie is a small piece of data that a user’s server sends to the user’s browser. The browser may store it and return it to the same server on subsequent requests. Typically, it can be used to indicate whether two requests are from the same browser to keep the user logged in. It holds useful state information for the stateless HTTP protocol.

The main scenarios for using cookies:

  • Session management – Login, shopping cart, game score, or any other information the server needs to remember
  • Profile – user preferences, themes, and other personality Settings.
  • Tracking – Records and analyzes user behavior

Cookies were once a common way to store data on the client side because it was the only way to store data. Modern storage APIS are now recommended. Cookies are included in every request, so they can affect performance (especially when requesting data on a mobile end).

There are two types of cookies:

  • Session cookies – Deleted when the client is closed. Web browsers can use session recovery techniques to solidify most session cookies as if the browser had not been closed.
  • Permanent cookies— As opposed to client shutdown and expiration,permanent cookiesWill expire at the specified expiration time or after a specified time (max-age).

Note that confidential and sensitive information cannot be saved or transmitted in HTTP cookies because the mechanism of cookies is inherently insecure.

Cookies are already widely supported in browsers

The cache

The cache interface provides a storage mechanism for cached Request/Response objects. Note that the cache interface is exposed to the window scope, just like the worker. Although the Cache is defined in the service worker thread specification, it does not necessarily have to be used with the service worker thread.

A single source can have multiple named cache objects. Developers need to implement how to handle update caches in scripts, such as in service worker threads. Objects in the cache are not updated unless requested by display, and will not expire unless they are deleted. Use cachestorage.open () to open the named cache object, and then call any cache method to maintain the cache.

Developers need to periodically clear cached entries. Each source has a limited amount of cached data on the browser side. Use StorageEstimate to estimate cache quota utilization. The browser tries to manage disk space, but it may delete cached data from a specified source. The browser may or may not delete all data from the specified source. Remember to use names for script versioning and only work on safe versions of scripts. See Deleting Old Caches for more information.

The CacheStorage interface represents Cache object storage.

Interface:

  • Provide a home directory for all named caches that can be accessed by serviceworkers or other workers
  • Maintains a mapping between a string name and a cache object

Create a Cache instance with cachestorage.open (). Use cachestorage.match () to check whether a given Request is a key of a Cache object in a CacheStorage object. CacheStorage is accessed through the global Caches property.

IndexedDB

IndexedDB allows you to persist data in your browser. It allows you to create an application that is rich in queries and doesn’t care about the network. Your application will work with or without a network. IndexedDB is suitable for applications with large amounts of data (such as DVD warehouse lending) that do not require a stable network to work (such as mail clients, spreadsheets, notebooks, etc.). IndexedDB has become more popular as web applications have become more complex. In this chapter we discuss some of the details.

Initialization with IndexedDB

IndexedDB allows the use of ‘keys’ to store and restore saved objects. All changes to a database are included in a transaction, and indexedDB follows the same origin policy. You can only access data under the same domain name.

IndexedDB is an asynchronous API that can be used in most contexts, including WebWorkers. Of course there was a synchronous version, but that’s been canceled.

IndexedDB once had a competitor, WebSQL, but WebSQL was abandoned by the W3C. WebSQL database is a relational data access system, while IndexedDB is an indexed table system.

Do not use IndexedDB based on the experience of other databases. Instead, you need to read the documentation. There are some key concepts to keep in mind:

  • IndexedDB stores key-value pairs-values can be objects of complex structure, and keys can be properties of those objects. You can index any property in an object for quick lookup, such as sorted enumerations. Keys can also be binary objects.
  • IndexedDB is based on a transactional data model —

Everything that is done in IndexedDB happens inside the transactional context. You cannot execute commands or open a cursor outside of a transaction. Similarly, transactions commit automatically, not manually

  • The IndexedDB API is mostly asynchronous – the API does not return data to you. Instead, you need to pass in the callback function. You can’t synchronously store or restore a value in a database. Instead, you need to request the execution of the database operation, and when the execution is complete, an event notification is sent. This event type tells the developer whether the operation was successful or not. This is very similar to the [XMLHttpRequest] operation.
  • IndexedDB requires a number of Request-Request objects to accept the event that the previously mentioned operation succeeds or fails. They have onSuccess and onError attributes, as well as readyState, result, and errorCode attributes, to tell the status of the request.
  • IndexedDB is object-oriented – Unlike a traditional database, IndexedDB is based on a set of columns and columns. This difference in patterns affects the way we build applications.
  • IndexedDB does not use SQL —

It uses index queries, which generate a cursor that can be used to traverse the result set of your query. If you are not familiar with NoSQL systems, you can read the Wikipedia article on NoSQL.

  • IndexedDB follows the same origin policy – the source is a collection of domain names, application layer protocols, and URL ports for executing script documents. Each source has its own database, and each database has a name that identifies the source.

Limitations of IndexedDB

IndexedDB is designed to accommodate most client storage situations. However, it is not designed to handle the following situations:

  • Internationalized collation – String collation differs from language to language because internationalized collation is not supported. Therefore, the queried data can be sorted by itself.
  • Synchronization – This API is not designed for synchronization with the server. You need to write your own code to handle client-server data synchronization.
  • Full-text search – there is no operation LIKE LIKE in SQL

In addition, the database is purged under the following conditions

  • User Request Cleanup – Many browsers allow users to erase data for a specific url, including cookies, bookmarks, passwords, and IndexedDB data.
  • Browser is Private mode – Some browsers have private mode or anonymous mode, which automatically clears the database when the user closes the session.
  • The disk capacity is slow. Procedure
  • Data is corrupted.

The exact circumstances and browser capabilities change over time, but the general philosophy of the browser vendors is to make the best effort to keep the data when possible. Specific environments and browser capabilities change rapidly, but browser manufacturers are moving toward preserving data as best they can.

Choose the appropriate storage API

As mentioned earlier, it is best to choose a widely used API with asynchronous capability. This naturally leads to the following technical points:

  • For offline storage, use [Cache API]. All browsers that support Service workers can support it. The Cache API is great for arranging associated resources with known urls.
  • Use IndexedDB to store application status and user-generated content. This allows users to use applications offline in more browsers than those that only support the Cache API.