Prize research | 1 TB hard drive when you take AI + block chain development trend and application research


1. What is browser caching?

Browsers typically cache frequently used resources on your PC’s disk and memory. For example, the Cache of Chrome is stored in the Cache folder and Media Cache folder in \Users\Your_Account\AppData\Local\Google\Chrome\User Data\Default.

2. What is static resource server?

In the general website, static resource use frequency is high, traffic occupation is large. For websites with relatively large traffic volume, static resources will be placed in the CDN server, which does not occupy the network bandwidth of the service server, and achieves better user experience.

3. Process for the browser to request static resources

For front-end developers, we work mostly with caches in the browser, so this is a simplified version of the process. In fact, static resource server (CDN) is usually used in practical applications.

4. Classification of browser cache

The graph below shows the result of a request for different resources on a certain website. It can be seen that some resources are read directly from the cache, some resources are re-validated with the server, and some resources are re-fetched from the server.

  • 200 from cache
  • 304 not modified

Note that everything we’ve discussed about caching resources is for GET requests only. Behavioral operations such as POST, DELETE, and PUT are usually not cached.

5. Cache-control and Expires

  • Cache-control is a new response header in HTTP1.1
  • Expires is a response header in HTTP1.0
  • Cache-control uses relative time
  • Expires specifies a specific expiration date, not a number of seconds. Since many servers and clients have clock inconsistencies, it is best to use cache-control.
  • Cache-control overrides Expires when both are used together

6. Cache-control which attributes can be set

  • Max-age (unit: s)

Specifies the maximum length of time for which the cache is set. After the browser sends a request to the server, the browser does not send any more requests to the server during max-age.

  • public

Specifies that responses can be cached in the proxy cache and thus shared by multiple users. If private is not explicitly specified, it defaults to public.

  • private

Responses can only be cached in private caches, not in proxy caches. Resources that are sensitive to user information usually need to be set to private.

  • no-cache

Indicates that you must verify with the server whether the resource has been changed (by if-none-match and Etag) before deciding whether to use the local cache.

  • no-store

It is absolutely forbidden to cache any resources, which means that each time a user requests a resource, a request is sent to the server, and the full resource is downloaded each time. Usually used for confidential resources.

For the use of cache-control, see the figure below

7. Freshness limit

HTTP maintains a copy of a server resource through caching for a period of time called freshness limits. This request for the same resource does not pass through the server again for a period of time. Cache-control and Expires can be used to set freshness limits. The former is the new HTTP1.1 response header, and the latter is the HTTP1.0 response header. Both do the same thing, but because cache-Control uses relative time, and Expires can be a bit of a client-side versus server-side issue, we prefer cache-Control.

The HTML code

<html> <head> <meta http-equiv="Content-Type" content="text/html; <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="IE=EDGE" /> <title>Web Cache</title> <link rel="shortcut icon" href="./shortcut.png"> <script> </script> </head> <body class="claro"> <img src="./cache.png"> </body> </html>Copy the code

Node server code

var http = require('http'); var fs = require('fs'); http.createServer(function(req, res) { if (req.url === '/' || req.url === '' || req.url === '/index.html') { fs.readFile('./index.html', function(err, Res.setheader (' cache-control ', "no-cache, max-age=" + 5); res.setheader (' cache-control ', "no-cache, max-age=" + 5); res.setHeader('Content-Type', 'text/html'); res.writeHead('200', "OK"); res.end(file); }); } if (req.url === '/cache.png') { fs.readFile('./cache.png', function(err, file) { res.setHeader('Cache-Control', "max-age=" + 5); Res.setheader (' content-type ', 'images/ PNG '); res.writeHead('200', "Not Modified"); res.end(file); }); } }).listen(8888);Copy the code

When the page is accessed a second time within 5 seconds, the browser retrieves the resource directly from the cache

8. Verify the server again

The expiration of a resource cached in the browser or proxy cache does not mean that it is actually different from the resource on the original server, only that it is time to check. This situation is called server revalidation.

  • If the resource changes, you need to fetch the new resource and replace the old resource in the cache.
  • If the resource has not changed, the cache simply needs to get a new response header and a new expiration time to update the resource expiration time in the cache.

HTTP1.1 recommends if-none-match /Etag, while HTTP1.0 uses if-modified-since/last-modified.

9. The Etag and If – None – Match

Etag is a hash string generated by the server to identify the resource status based on the entity content. The browser passes this string back to the server to verify that the resource has been modified. If not, the process is as follows:

Code sample

var http = require('http'); var fs = require('fs'); http.createServer(function(req, res) { if (req.url === '/' || req.url === '' || req.url === '/index.html') { fs.readFile('./index.html', function(err, Res.setheader (' cache-control ', "no-cache, max-age=" + 5); res.setheader (' cache-control ', "no-cache, max-age=" + 5); res.setHeader('Content-Type', 'text/html'); res.writeHead('200', "OK"); res.end(file); }); } if (req.url === '/shortcut.png') { fs.readFile('./shortcut.png', function(err, file) { console.log(req.url) res.setHeader('Content-Type', 'images/png'); res.writeHead('200', "OK"); res.end(file); }) } if (req.url === '/cache.png') { fs.readFile('./cache.png', function(err, file) { console.log(req.headers); console.log(req.url) if (! req.headers['if-none-match']) { res.setHeader('Cache-Control', "max-age=" + 5); res.setHeader('Content-Type', 'images/png'); res.setHeader('Etag', "ffff"); res.writeHead('200', "Not Modified"); res.end(file); } else { if (req.headers['if-none-match'] === 'ffff') { res.writeHead('304', "Not Modified"); res.end(); } else { res.setHeader('Cache-Control', "max-age=" + 5); res.setHeader('Content-Type', 'images/png'); res.setHeader('Etag', "ffff"); res.writeHead('200', "Not Modified"); res.end(file); }}}); } }).listen(8888)Copy the code

10. How to calculate the Etag value

  • The ETag value is typically computed by the server and returned to the client in response to a client request
  • ETag header information can be easily obtained by timestamp; But it’s not recommended, because it’s the same as the last-Modified header, right
  • An ETag value can be anything that uniquely identifies a resource, such as the version associated with a resource in persistent storage, one or more file attributes, entity header information and CheckSum, or a hash of computed entity information.
  • Sometimes, calculating an ETag value can be costly, and you can use methods such as generating unique values (such as the common GUID).
  • By default, Apache automatically generates eTags by setting the FileEtag INode Mtime Size in FileEtag.
  • Because eTags are constructed by the server, it is important to ensure that eTags are unique in a clustered environment

11. The if-modified-since and last-modified

These are request/response headers used in HTTP1.0 to verify that a resource is expired. Both headers are dates, and the validation process is similar to Etag, which is not covered here. When using these two headers to verify that a resource is up to date, there are the following problems:

  • Some document resources are periodically rewritten, but the actual content does not change. In this case, the file metadata will show that the last Modified date of the file is different from if-modified-since, resulting in an unnecessary response.
  • Some document resources have been modified, but the changes are not significant enough to require all caches to be updated (such as code comments)

12. To summarize

  • The browser cache is divided into 200 from cache and 304 not Modified
  • Cache-control and Expires can be used to set freshness limits. The former is the new HTTP1.1 response header, and the latter is the HTTP1.0 response header.
  • Max-age (in seconds) whereas Expires specifies a specific expiration date, not a number of seconds
  • Cache-control overrides Expires when both are used together
  • The client doesn’t care how the ETag value is generated, as long as the service sends it the ETag value when the state of the resource changes, right
  • By default, Apache automatically generates eTags by setting the FileEtag INode Mtime Size in FileEtag.
  • ETag, along with if-none-match or if-match, is sent by the client to the server via HTTP headers (including the ETag value).
  • Last-modified is often used with if-modified-since by the client to include last-Modified values in the HTTP header sent to the server for processing.
  • Some document resources are periodically rewritten, but the actual content does not change. In this case, the file metadata will show that the last Modified date of the file is different from if-modified-since, resulting in an unnecessary response.

13 demo

demo

【 Editor’s Recommendation 】

  1. Top 10 Skills for Front-end Engineers
  2. How does backend development feel? Front end program ape pay big exposure
  3. 12 top Skills a front-end developer must Master
  4. Summer dry goods! August 2017 Super practical dry goods collection for front-end developers
  5. Ten free web front-end development tools – Envato – Medium

Yan-ni zhang



Thumb up 0