The cache

Why cache?

Caching is actually quite common in life. Often the first time you open a new software or web page is relatively slow, but the second time you open it is much faster, thanks to caching. Greatly improved efficiency, also greatly improved user experience.

What data can be cached?

Data that cannot be cached

  • Update replacement data in real time (e.g., bullet screens, messages, comments, frequently changed AD images)
  • The HTML structure of a web page, which changes as the page is used

Data in cache

  • Static resources images that rarely change (e.g., product images, user avatars, website logos)
  • Used video data, used audio data will be in the cache

Technical level caching – Web caching

In front-end development, performance has always been a key issue, judging the performance of a website is to see the speed of page opening. However, improving the responsiveness of Web pages requires the use of Web caching.

Advantages of Web caching:

  • Network resources are saved
  • Improved network efficiency
  • Shorten the distance of web page request resources
  • Reduce network latency
  • To reduce the bandwidth
  • Reducing network Load

Types of Web caches:

1. Database cache

  • Cache database query results to speed up access, reduce database access times, relieve database pressure, and improve web application speed

2. Proxy server cache

  • HTTP requests satisfied by proxy servers when the server cannot be accessed (example: cross-domain Porxy)

CDN cache

  • By placing node servers across the network to distribute static content quickly and reliably,

4. Browser cache

  • Speed up browsing. The browser stores the requested resource on the user’s disk. When the page is requested again, the browser can retrieve the resource locally and respond to the user, thus speeding up page browsing

Browser cache

Browser caches include HTTP cache, indexDB, cookie, localStorage, and sessionStorage

1. HTTP cache (mandatory cache & negotiated cache)

Mandatory cache

What is mandatory caching

  • The requested resource is in the local cache. The resource is obtained from the local cache, and no request is required
  • To understand mandatory caching, what is cache control

The cache control

In HTTP, there are two properties that Control the Cache switch: Pragma and cache-Control.

Pragma

There are two cases of Pragma Pragma and Expires.

  • Pragma has the value no-cache: indicates that caching is disabled
  • The Expires value is a time (Greenwich Mean Time) : indicates how long the cache will be valid

Note: When both Pragma and cache-control are present in the HTTP response header, the cache-control execution priority from high to low is Pragma ==> cache-control ==> Expires

Cache-control

Cache-control In HTTP request and response headers, used to Control the HTTP Cache

Cache-control instructions in common request headers

  • Cache-control: max-age=

    : indicates the maximum period of Cache storage
  • Cache-control: max-stale[=

    ] : indicates that a client is willing to accept an expired resource
  • Cache-control: no-cache: revalidate Cache (negotiated Cache validation)
  • Cache-control: no-store: disables Cache

Cache-control instructions in common response headers

  • Cache-control: must-revalidate The request for the expired resource
  • Cache-control: no-cache request to verify Cache (negotiated Cache validation)
  • Cache-control: no-store does not use any Cache
  • Cache-control: private Approves local browser caching

Check the official documentation for details

Enforce the execution flow of the cache

Process Scenario 1 – Initial request

The browser makes a request to the server ==> The server receives the request from the browser and carries cache-control in the response header to the client (cache-control is the maximum expiration time of the Cache).

Process Scenario 2 – Request the same data again

The browser first checks to see if cache-control has expired ==> No expiration ==> The browser pulls the resource directly from the Cache (this process does not go through the server)

Process Scenario 3 –Cache-Controloverdue

Cache-control expires ==> No data can be pulled from the cache ==> Continue with Flow Scenario 1

Negotiate the cache

What is a negotiation cache? A negotiation cache is also called a comparison cache. A caching strategy for the server

  • The server determines the resources of the client
    • return304Indicates that the resource in the cache is consistent with the requested resource,
    • return200Represents the latest resource returned from the server.
  • To understand negotiated caching, what is cache validation

Cache invalidation

How to determine whether cached data is valid and verify that the cache is up to date (as well as the latest data in the server)

  • There are two attributes (resource identifier) in the response header,ETag and Last-Modified, that help the server control the client’s cache validation.

Last-Modified

  • Value is the last modification time of the resource, corresponding to the request header attributeIf-Modified-Since 

Etag

  • ETagIs a new attribute added to HTTP1.1
  • A unique identifier for a resource, like an ID, is unique. The corresponding request header isIf-None-Match 。
    • EtagIs essentially a string

Note: Etag is preferred when both Last-Modified and Etag are present in the response header.

The execution flow of the negotiation cache

Process Scenario 1 – Initial request

The client sends a request to the server. ==> The server receives the request. ==> The response resource and its corresponding resource label (Etag or Last-Modified) are identified to the client

Process Scenario 2 – Request again

If the browser makes a request again ==> the request header will carry if-none-match (or if-modified-since) to the server ==> the server will if-none-match (or if-modified-since) with its own Etag(or Last-modified) (both cases)

  • Returns if it is equal304Indicates that the cache resource is consistent with the client resource
  • If not, return200And returns the resource and newEtag(orLast-ModifiedThe value of).

Negotiation Cache Flow chart

Note: When you refresh the browser page, the forced cache is invalidated, whereas the negotiated cache is valid.

2 . indexDB

IndexedDB is a browser-provided local database that can be created and manipulated by web scripts. IndexedDB allows you to store large amounts of data, provide a lookup interface, and build indexes. These are all things that LocalStorage does not have. In terms of database type, IndexedDB is not a relational database (it does not support SQL query statements) and is closer to a NoSQL database.

Please refer to official documentation for details:

3 . Cookie

What is a Cookie

  • Cookie means a small Cookie. Used for data caching, cookies hold a very small amount of data and are limited in size to 4KB. You can cache user login information (for example, token).

The role of the Cookie

  • Cookie cached data is always carried in same-origin HTTP and passed between the browser and the server
  • Cookie cache can do data persistence, Cookie data is valid before the set Cookie expiration time (data in the cache close browser window can not delete Cookie data)

The use of cookies

  • Download the dependency package: NPM I js-cookie or YARN add Js-cookie
  • Import Cookies from ‘js-cookie’
  • Save data syntax:Set (' key ', 'value ',{Expires: 7, PATH:'})
    • The third argument is an object whose properties areexpiresandpath
    • Expires: Creates an expired cookie with a value of days
    • Path: The Cookie is valid only for the page in the current path
  • Use data syntax: cookie.get (‘ key ‘)

Note: Cookies have the concept of path, you can restrict the path of the Cookies data

4 . localStorage

1. LocalStorage function: localStorage

  • Classic scenario: Login is not required

2. LocalStorage syntax:

  • 2.1 Save data: localstorage.setitem (‘ attribute name ‘, attribute value)
  • 2.2 Fetch data: localstorage.getitem (‘ Property name ‘)
  • Localstorage.removeitem (‘ attribute name ‘)
  • 2.4 Clearing Data: localstorage.clear ()

3. LocalStorage features:

  • 3.1 localStorage is permanent storage and will always exist unless manually cleared.
  • 3.2 localStorage Can only store string data. If it is a different type, it is automatically converted to a character format for storage.

5 . sessionStorage

1. SessionStorage Function: temporary storage

  • Classic scenario: value transfer between pages

LocalStorage: sessionStorage: localStorage

  • Sessionstorage.setitem (‘ attribute name ‘, attribute value)
  • Sessionstorage.getitem (‘ attribute name ‘)
  • Delete the data: 2.3 sessionStorage. RemoveItem (‘ attribute name)
  • 2.4 Clearing data: sessionStorage.clear()

3. SessionStorage features:

  • 3.1 sessionStorage page will be automatically cleared after closing.
  • 3.2 sessionStorage can only store string data. If it is a different type, it is automatically converted to a character format for storage.

Cookie, localStorage, sessionStorage similarities and differences

Cookie localStorage sessionStorage
Data retention period Generally generated by the server, you can set the storage time. You need to manually clear the disk; otherwise, the disk is saved permanently This parameter is valid only on the current page and is cleared after you close the page or browser
Data storage size Less than 4 KB 5 MB or larger 5 MB or larger
Relationship with the Server Each time it is carried in the HTTP header and passed between the browser and the server Save with the client hard disk, do not participate in the communication with the server It is stored in the client memory and does not communicate with the server