17

Browser storage

Cookie

Cookie is a stateless protocol of HTTP protocol. When requesting the server, all HTTP requests need to carry cookies to verify the user's identity. Cookie is generated by the server, stored on the client, and used to maintain the state of

Usually cookies consist of the following values:

 名称(name)
 值(value)
 域(Domain)
 值(value)
 路径(Path)
 失效时间(Expiers/Max-Age)
 大小(Size)
 是否为 HTTP 请求(HttpOnly)
 安全性(Secure)

 提示:域、路径、失效时间和安全性都是服务器给浏览器的指示,它们不会随着请求发送给服务器,发送给服务器的只有名称与值对。

Cookie has some limitations , it can be set with an expiration time, but if it is not set, it will be at the same level as the session, and it will disappear once the browser is closed.

Cookie has the following advantages:

  • The expiration time can be controlled, it will not be effective forever, and there is a certain degree of security.
  • It can be extended and shared across domains.
  • Through encryption and secure transmission technology (SSL), the possibility of cookies being cracked can be reduced.
  • Have higher compatibility.

disadvantages of 161710fffb8bae are as follows:

  • There are certain number and length restrictions. Each cookie cannot exceed 4KB in length, otherwise the excess part will be truncated.
  • The data in the request header can be easily intercepted and attacked.
  • The size of a single cookie does not exceed 4KB, and many browsers limit a site to save a maximum of 20 cookies.

web Storage

H5 can store the user's browsing data locally. Cookies were used in the past, but web storage is faster and safer. A large amount of data can be stored without affecting the performance of the website. It exists as a key/value pair.

web Storage is divided into two types: sessionStorage and localStorage.

sessionStorage

sessionStorage stores data in the session and disappears when the browser is closed. It has the following characteristics:

- 大小 5Mb
- 页面刷新数据不会消失,页面关闭就消失。
- 不可以跨页面(仅在当前页面使用)。
- 使用 window.open 打开页面和改变 location.href 方式可以获取到 sessionStorage 内部的数据。

Mainly used in the following scenarios:

  • Mainly for the storage of session-level small data.
  • Store some information that still needs to be stored when the current page is refreshed, but does not need to be left after closing.
  • Very suitable for the use of single-page applications, can be used to store login status information, etc.

localStorage

localStorage will always store the data locally on the client. Its API provides the following methods to operate:

  • setItem (key, value) —— save the data, store it in the form of key-value pairs.
  • getItem (key) —— read the data, pass in the key (key), and get the corresponding value (value).
  • removeItem (key) —— delete a certain data, delete a key-value pair.
  • clear () —— delete all data.
  • key (index) —— Get the key of an index.

The following are the features of localStora:

- 大小 5Mb。
- 可以跨页面。
- 永久存储,需要手动删除。
- 使用 window.open 打开页面和改变 location.href 方式可以获取到 sessionStorage 内部的数据。

It is usually used in the following scenarios:

  • The client data is saved persistently and can only be deleted through JavaScript or the user clears the browser cache.
  • If there is some large amount of data, such as the automatic saving of the editor, etc.
  • Access common data between multiple pages. sessionStorage can only be used for one tab, while localStorage can be shared among multiple tabs.

Browser caching mechanism

The browser’s caching mechanism is to cache the accessed resources so that when the client accesses it next time, it can directly access the cached resources, thereby reducing the number of server requests and allowing the page to load faster.

And judging whether to access the cache depends on various HTTP headers, such as the following:

  • Expires: The response header indicates the expiration time of the resource.
  • Cache-Control: request header/response header, is the cache control field.
  • Etag (HTTP1.1): The response header is the resource identifier and is stored by the server. Once the resource is modified, the Etag will change accordingly.
  • lf-None-Match (HTTP1.1): Request header. Generally, the server will compare If-None-Match with the latest ETag of the requested resource.
  • Last-Modified (HTTP1.0): The response header indicates the time when the resource was last modified.
  • If-Modified-Since (HTTP1.0): request header, the last modification time of the resource (details later).

These headers together constitute HTTP requests and responses, and also support browser caching, but this caching method is flawed.

First of all, if the resource update rate is in units of seconds or less, then this cache cannot be used. Because the minimum time unit is seconds.

Second, if the file is dynamically generated by the server, the update time of this method is always the time of generation. Even if the file may not change, it will be updated automatically, so it will not serve as a cache.

strong cache

Usually the server will notify the browser of a cache time, this information is in Cache-Control and Expires, the browser judges whether the cache is expired through this information. If the time has not expired. It is taken directly from the cache. This is the so-called "strong cache".

Expires

In HTTP1.0. Use the Expires field to indicate the expiration time of the cache, that is, the effective time + the time of the server at that time. But the disadvantage of this approach is that the user only needs to modify the client's local time. When the client and server time are inconsistent, the browser will judge that the cache is invalid, and then request the resource again.

Cache-control

Cache-Control is a response header for caching in the HTTP protocol. It can consist of the following values:

  • max-age: used to set the maximum period of the cache. Contrary to Expires, its time is relative to the time of the request.
  • s-maxage: Same as max-age, only used for shared cache, such as CDN cache.
  • public: Correspondingly, it can be cached by any object, even content that is normally not cacheable.
  • private: The cache can only be cached by a single user, and cannot be used as a shared cache (that is, the proxy server cannot be cached).
  • no-cache: It can be cached on the client side, but must go to the server to check the freshness every time to decide whether to obtain the latest resources from the server (200) or read the cache (304), that is, negotiate the cache.
  • Store-NO: not allow the client stores , each time requesting a new resource from the server.

Negotiation cache

If the strong cache is missed, that is, the strong cache is invalidated (maybe no-store or no-cache is set in Cache-Control), then it is judged to negotiate the cache.

Last-Modified & If-Modified-Since(HTTP1.0)

When the resource is requested for the first time, the server will return the time when the resource was last modified. When requesting again later, the server will compare the If-Modified-Since and Last-Modified fields. If the two are the same, it means that the resource has not been modified, and a 304 status code is returned. If the two are different, it means that the resource has been modified, so the data and the 200 status code are returned (no request was sent).

However, if the time unit for the server to update the resource is seconds, the above-mentioned method cannot identify multiple modifications within one second. At the same time, if the resource update speed is less than 1ms, it is impossible to generate a new last modification time. In order to avoid this situation, a new set of fields appeared in HTTP 1.1: Etag and If-None-Match.

Etag & If-None-Match (HTTP1.1)

Etag is an attribute of HTTP1.1. It is generated by the server and returned to the client, and has a higher priority than Last-Modified.

In HTTP1.1, when the browser initiates an HTTP request for the first time, the server returns an Etag. When the browser initiates the same request for the second time, the client will send an If-None-Match whose value is Etag. The server compares the Etag sent by the browser with the Etag of the server, and if they are the same, it sets the value of If-None-Match to false and returns 304, indicating that the browser cache is used. If they are different, the server sets the value of If-None-Match to true and returns 200 and the new data.

The speed up of web page loading is not only achieved by speeding up the Internet speed. Behind our smooth access, the browser storage and caching mechanisms are also indispensable. I hope this article can help you increase your understanding of this mechanism.

Reference materials:

In-depth understanding of browser caching mechanism https://www.jianshu.com/p/54cc04190252

One article to understand the front-end cache https://juejin.cn/post/6844903747357769742?utm_source=gold_browser_extension

Browser storage and caching mechanism https://blog.csdn.net/wantingtr/article/details/100559520

Recommended reading

What is the meaning of 404 when

-wide HTTPS necessarily safe?


云叔_又拍云
5.9k 声望4.6k 粉丝

又拍云是专注CDN、云存储、小程序开发方案、 短视频开发方案、DDoS高防等产品的国内知名企业级云服务商。