Network level caching

1. Strong cache

Strong caching is mainly controlled by cache-Control and Expires fields in the response header. Where Expires is defined in HTTP 1.0, it specifies an absolute expiration period. Cache-control is a Cache Control field from HTTP 1.1. Cache-control :max-age defines a maximum lifespan from the time a document is first generated until the Cache is no longer valid. Because Expires is a product of the HTTP1.0 era, it was designed with a few flaws that can lead to cache errors if the local time and server time diverged too much. Cache-control has a higher priority when both fields are used together. The effect of these two fields is similar, and the client checks whether the cache is available by comparing the local time with the server lifetime. If the cache does not exceed its lifetime, the client simply adopts the local cache. If the expiration date has passed, the cache is invalidated. The client then communicates with the server again to verify that the cache needs to be updated. Added: refresh, back will skip the cache.

2. Negotiate cache

Strong caching if a cache failure is detected, server revalidation is required. This caching mechanism is also known as negotiated caching. When the browser first gets a request, it carries either the last-modified or Etag of the resource in the response header. The subsequent request server determines whether the resource is invalid based on the if-Modified-since and if-none-match fields in the request header. Once the resource expires, the server sends a new resource to the client to ensure the validity of the resource. Note that when both Etag and Last-Modified are present in the response header, the Etag is compared first, followed by last-Modified.

3. The CDN cache

A CDN is used to cache static resources. When a user sends a request, it preferentially returns static resources from the CDN nearest to the request.

Caching in the browser

1. cookie

Because HTTP is stateless, if the HTTP state needs to be recorded, the browser needs to record the operation, the client sends a request, the server returns an identifier to record the request state, and the client saves it in the cookie. This API is:

get:document.cookie
set:document.cookie='key=value'
Copy the code

2. session

The session is stored on the server, but also based on cookies, and then stored on the server

3. localStorage

Browser local storage, can store the size of 2m related API:

//get
localStorage.getItem('key')
//set
localStorage.setTtem('key'.'value')
//remove
localStorage.removeItem('key')
//clear all
localStorage.clear()
Copy the code