Browser static resource caching policy

The browser actually provides two control strategies, one is mandatory cache and the other is negotiated cache

Mandatory cache

  • Forced cache: is to force the use of browser cache down resources;

    • Use your own cached files for a specified period of time, and you don’t need to request them again.

    • This is implemented by adding a Response Headers field to the request to indicate how long the request will not be required. This field is http1.0, cache-control, or http1.1. If both fields exist at the same time, 1.1 must have a higher priority than 1.0.

Negotiate the cache

  • Negotiated cache: the browser and the server need to negotiate whether to use the browser cache or the server cache.

    • If the Response Headers field is last-modified in http1.0 or Etag in http1.1, 1.1 has a higher priority than 1.0. If the Response Headers field is last-modified, 1.1 has a higher priority than 1.0.

    • If both the forced cache and negotiated cache fields exist, the forced cache takes precedence.

The advantages and disadvantages of the two cache strategies are compared:

  • The disadvantage of forced caching is that the server file may be updated during the forced period and the browser may not be able to read the latest resources.
  • The disadvantages of negotiating cache are: each time you have to send a request to ask whether the server resources are updated, which may cause unnecessary waste of time and traffic.

Is there a compromise solution?

A: Add file fingerprints and associate file namesCopy the code

Refer to a file in HTML with the file fingerprint added

The entry file used to access a web page is HTML (the backend template file can also be regarded as HTML). This policy is: - Never cache THE HTML, always use the latest version of the server,Copy the code
  • When the browser renders the HTML, it loads the resource file referenced in it

  • If each resource file is set to a mandatory cache, and set to a long expiration time, how does the browser obtain the latest version of the file?

  • Is very simple, such as a picture has had the change, then this image file fingerprints will change, involving all resource file will then cascade change, cited the picture style sheet CSS file will also change (because the image name changed), and cited the stylesheet entry document HTML will also change subsequently (because the style sheet name changed), The next time the user accesses the entry HTML file, the user will naturally load the “new file” with the changed name.

  • This is perfect, the implementation of the file does not change when the local cache, the file changes on the server side of the latest, always keep the latest fastest.

    reference

Server-side static resource caching policy: Nginx static resource caching policy configuration