In addition to native apps, phones now have “WebApps” that run on the go. A good WebApp can even have the same functionality and experience as a native App.

In my opinion, WebApp is the product of our front-end performance optimization, the result of our front-end engineers’ unremitting pursuit of experience, and a “declaration of war” on the performance of Web pages against Native applications.

WebApp’s excellent performance can be attributed to the widespread use of browser storage technology — local storage, in addition to caching, as we mentioned in the previous section.

Where the story begins: With Cookie

The job of a Cookie is not to store it locally, but to “maintain state.”

In the early days of Web development, one of the most urgent issues was state management: HTTP was a stateless protocol. The server received a request from a client, returned a response, and the story ended there. The server did not record any information about the client. So how do you let the server know “I’m me” the next time you make a request?

In this context, cookies came into being.

A Cookie is basically a small text file stored in a browser, attached to an HTTP request, that flies back and forth between the browser and the server. It can carry user information, and when the server checks the Cookie, it can get the status of the client.

For details about cookies, you can view them in the Application panel of Chrome:

As you can see, cookies exist in the form of key-value pairs.

Performance disadvantages of Cookies

A Cookie is not big enough

As you know, cookies have a maximum size limit of 4KB. When the Cookie exceeds 4KB, it will face the fate of cutting. In this way, cookies can only be used to access a small amount of information.

Excessive cookies can lead to a huge performance waste

Cookies follow the domain name. We specify the Cookie value to store via set-cookie in the response header. By default, domain is set to the hostname of the Cookie page. We can also set the value of domain manually:

Set-Cookie: name=xiuyan; domain=xiuyan.me
Copy the code

All requests under the same domain name carry cookies. Imagine if we were just asking for an image or a CSS file at the moment, and we were also carrying around a Cookie (the key is that the Cookie holds information I don’t need right now). Although cookies are small, there can be many requests. As the requests pile up, the overhead of such unnecessary cookies will be unimaginable.

As front-end applications have grown in complexity, the Cookie has evolved into a storage generalist — not only used to maintain state, but also stuffed with a jumble of other information and forced to take on the burden of local storage. In the absence of a better local storage solution, Cookie’s tiny body is burdened with more than 4KB of memory can handle.

In order to make up for the limitations of cookies, let “professional people do professional things”, Web Storage appeared.

Step forward: Web Storage

Web Storage is a data Storage mechanism provided by HTML5 specifically for browser Storage. It is divided into Local Storage and Session Storage. These two sets of concepts are very similar, so we might as well understand the differences between them first, and then study their commonalities.

Local Storage and Session Storage

The difference lies in the lifecycle and scope.

  • Life cycle: Local Storage is persistent Local Storage. Data stored in it will never expire. The only way to make it disappear is to manually delete it. Session Storage is temporary local Storage. It is session-level Storage. When the Session ends (the page is closed), the Storage content is also released.

  • Scope: Local Storage, Session Storage, and Cookie all follow the same origin policy. However, the special point of Session Storage is that even if two pages under the same domain name are not opened in the same browser window, their Session Storage content cannot be shared.

Features of Web Storage

  • Large Storage capacity: Web Storage The Storage capacity ranges from 5 to 10 MBIT/s depending on the browser.

  • It is only on the browser side and does not communicate with the server.

Web Storage core API usage example

The data stored in a Web Storage is text content in the form of key-value pairs, just like cookies. Local Storage has the same API as Session Storage. Here we use localStorage as an example.

  • Store data: setItem()
localStorage.setItem('user_name'.'xiuyan')

Copy the code
  • Read data: getItem()
localStorage.getItem('user_name')

Copy the code
  • Remove data corresponding to a key name: removeItem()
localStorage.removeItem('user_name')

Copy the code
  • Clear data records: clear()
localStorage.clear()

Copy the code

Application scenarios

Local Storage

Local Storage has no special restrictions on Storage. In theory, all data Storage tasks that cookies cannot handle and can be accessed by simple key-value pairs can be entrusted to Local Storage.

Here is an example. Considering that one of the characteristics of Local Storage is persistence, sometimes we prefer to use it to store some stable resources. For example, image-rich e-commerce sites will use it to store Base64 image strings:

Some websites also use it to store static resources such as CSS and JS that are not updated frequently.

Session Storage

Session Storage is more suitable for storing life-cycle and session-level information that it synchronizes. This information only applies to the current session and needs to be updated or released when you start a new session. For example, the Session Storage of Weibo is mainly used to store the browsing footprint of this Session:

Lasturl corresponds to the lasturl you visited, which is immediate. It updates when you switch urls, and there’s really no point in keeping it when you close the page, just release it. Such data is best handled by Session Storage.

In this case, Web Storage is powerful enough. So can Web Storage hold all Storage scenarios?

The answer is no. As you can see, Web Storage is a very simple thing from definition to use. It is stored as key-value pairs, which is a bit like an object but not even an object — it can only store strings, and to get an object we need to parse the string one more time.

Ultimately, Web Storage is an extension of cookies, which can only be used to store small amounts of simple data. When it comes to large, complex data, Web Storage can’t help. At this point we need to know our final big boss — IndexDB!

Final form: IndexDB

IndexDB is a non-relational database that runs on a browser. Since it is a database, it is not 5M, 10M, such a small level of play. Theoretically, IndexDB has no storage upper limit (generally no less than 250MB). It can store binary data as well as strings.

IndexDB has had excellent tutorials since its inception, and we won’t go into the details of how it works today. Next, we followed MDN’s recommended operating pattern through a basic IndexDB usage process designed to give a sense of IndexDB:

  1. Open/create an IndexDB database (if the database does not exist, the open method will create a new database named xiaoceDB).
// In the following callback, we can get the database instance via event.target.resultletDb // 1 bit database name, 2 version number const request = window.indexeddb.open ("xiaoceDB", 1) // Request. Onerror =function(event) {
     console.log('IndexDB cannot be used'} // Request. Onsuccess =functionDb = event.target.result console.log(event.target.result console.log)"You opened IndexDB")}Copy the code
  1. Create an Object Store (object Store mapped to a “table” unit in the database).
The // onupgradenneeded event is called when an update has occurred to the initial database/version and we create object Store requester. Onupgradenneeded = in its listener functionfunction(event){
  letObjectStore // If the same table has not been created before, create a new onetesttableif(! db.objectStoreNames.contains('test')) {
    objectStore = db.createObjectStore('test', { keyPath: 'id'}}})Copy the code
  1. Build a transaction to perform some database operations, such as adding or extracting data.
Const transaction = db.transaction(["test"]."readwrite"Const objectStore = transaction.objectStore()"test"Objectstore. add({id: 1, name:'xiuyan'})

Copy the code
  1. Wait for the operation to complete by listening for the right type of event.
// Transaction. Oncomplete =function(event) {
    console.log("Operation successful")} // The listener function in case of an operation failure, transaction.onerror =function(event) {
    console.log("There's an Error here.")}Copy the code

Application scenarios of IndexDB

As you can see from the above example, IndexDB allows you to create multiple databases, multiple tables in one database, and multiple data stores in one table — enough to hold complex structured data. IndexDB can be seen as an upgrade to LocalStorage, and when the complexity and size of the data becomes too large for LocalStorage to handle, IndexDB can no doubt be enlisted to help.

summary

The emergence and development of browser cache/storage technology has brought infinite opportunities for our front-end applications. In recent years, there are a lot of third-party libraries based on cache/storage technology, and excellent Web application models like PWA have been derived. It can be said that modern front-end applications, especially mobile applications, can develop to the point of challenging Native in experience mainly due to the achievements of cache/storage.