Newly developed nailing micro-application with React, found two problems after going online:

1. After each update, users need to manually refresh to get the latest HTML and THE latest JS, which is often joked by customers why the bug has not been changed. In fact, it has been changed, but the customer’s mobile phone is still running the old version.

2. When no caching policy is set, huawei phone requests JS and CSS again every time, no matter whether there is a local cache. The opening is slow and the experience is very poor.

In order to solve these two problems, the caching policy of HTML files is set to negotiation cache, that is, every time the server is asked whether the local latest, if the latest, the server returns 304 and does not transfer the file, the local load cache file; If the local file is not new, the server returns the latest file, displays the latest file locally and updates the local cache. The browser asks if ETag and last-Modified have been used locally.

The ETag is generated by Nginx using the following rules:

File last modification Time Hexadecimal – File length in hexadecimal format. For example, ETag: 59e72C84-2404 File length

10Base for - >9220to16Base - >2404
Copy the code

File last modified:

Standard date format ->Sat,21 Oct 2017 09:14:34GMT convert to second ->1508322436to16Base - > e72c84 59Copy the code

As long as the HTML file is updated, the browser will reload the HTML file. After the update, the user will not run the old version of the problem. Solve problem 1.

Huawei phones do not use the cache by default. To save bandwidth and improve user loading speed, you must use the cache for JS, CSS, and common static resources. Since The JS and CSS file names change every time react is packaged, there is no need to worry about the browser running the old version of the code due to strong caching. This solves the second problem.

The following is the Nginx configuration to set HTML file negotiation cache, JS, CSS strong cache

location /test/ { ... # Other configuration... if ($request_uri ~* .*[.](js|css|map|jpg|png|svg|ico)$) { add_header Cache-Control "public, max-age=2592000"; #} if one month than HTML Cache ($request_filename ~ * ^. * [.] (HTML | HTM) $) {add_header cache-control "public, no - Cache". # HTML file negotiation cache, that is, ask the server if the browser is new or not, if the server is not new, return the latest}}Copy the code

Attach browser cache rules:


Reference: juejin. Cn/post / 684490…