Practical application of front-end browser caching principle

foreword

The principle of browser caching is a classic question that must be asked in front-end interviews, and it is also the knowledge that front-end development must master. This article introduces the application of browser cache in actual projects. I hope that friends who are lucky enough to read this article are not only preparing for interviews, but really master this knowledge point. If you are lazy, you can answer the interview questions after reading the simple summary of the article. If you want to know more, you might as well read the article.

A brief overview of strong caching and negotiation caching

Strong caching and negotiation caching refer to the use strategy of browsers requesting static file (js, html, css, pictures and other files) caching, which is used to improve page loading speed.
The process of using the cache in the browser is: first perform strong caching, check whether there is such a file locally, whether the status of the file (expires and cache-control) has expired, and if it is not expired, directly use the local cache without sending a request to the browser. If it expires, execute the negotiation cache, ask the server if you can continue to use the cache (last-modified and etag), if you can, continue to use the local cache, if not, load a new file.
The cache setting priority is:
Cache-Control > expires > Last-Modified|etag

The status code of the strong cache is 200 (from memory cache) and
the status code of the negotiated cache is 304

practical application

strong cache

From the previous brief summary, once the expiration time is set, the browser will not send a request to the server when it has not expired, which will cause your server to actually update the file, but the browser does not know, so strong cache Must be used with caution.
HTML must be added without strong cache configuration, otherwise you may need the customer to clear the browser cache to see your code update
The following is the HTML configuration,

<head>
	<meta http-equiv="Pragma" content="no-cache">
	<meta http-equiv="Cache-Control" CONTENT="no-cache">
	<meta http-equiv="expires" content="-1">
</head>

But the above meta may be useless after adding it. At this time, you have to look at the configuration of the server side. Here we only talk about nginx

location ~ .*\.(htm|html )$ {
    
    
	add_header Pragma "no-cache";
	# 60秒内不会访问服务器
	# add_header Cache-Control "max-age=60";
	# 不缓存
	add_header Cache-Control "no-cache";
	add_header expires -1;
	
}
#过期时间为30天示例
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
    
    
	expires 30d;
}
# 时间设置永不过期示例
location ~ .*\.(js|css)$ {
    
    
	expires max;
}

In fact, when resources such as js, css and pictures are packaged by webpack, a random number (hash) will be added to the file name. Every time the page is updated, the new static file is actually accessed, so the strategy we adopt when using it is never Expired. You can look at the dist folder.
insert image description here
Strong caching is basically done with O&M and webpack, so friends who don’t know much about caching don’t feel that they are actually using them.
But once your server and html are not configured, the browser will judge and use its own configuration. The result of not configuring anything is that the cache time is uncontrollable and the performance is poor.

negotiation cache

Negotiation caching is more used for static file servers (such as CDN), which is part of active optimization. It needs to be configured not to use strong caching, or strong caching has a time limit.
For example, every time we package a project, a random hash number is added to the picture, which causes the picture to be reloaded every time the version is updated, but in fact, our pictures do not change easily in many cases. At this time, it would be better to save the pictures on a separate static file server or CDN, but we also need to ensure that the pictures can be updated when they really need to be updated, so the negotiation cache comes in handy at this time. (cdn is recommended for c-end projects. If you are interested, you can search for cdn-related articles, and the author will write in the future.) The
negotiation cache is mainly the server-side configuration. Here is nginx

# 开启Last-Modified方式二
location ~* \.(gif|jpg|jpeg|png|bmp|swf)$ {
    
    
	# 开启关闭etag,有些版本默认开启有些默认关闭,按需配置
	etag off|on;
	# 开启Last-Modified方式一,默认是开启的 on
	if_modified_since off|on;
	# 自定义Last-Modified的时间可以手动触发刷新,要配合if_modified_since off, 慎用
	add_header  Last-Modified 'Fri, 12 May 2006 18:53:33 GMT';
	# 不想要就置空
	# add_header  Last-Modified ""; 
	add_header  Cache-Control "public";
	# 设置不用用强缓存
	expires -1;
}

In fact, negotiation caching is also enabled by default in nginx1.7.3 and above versions, so you just need to make sure that the files that need to use negotiation caching are not strongly cached.

Last-Modified does not need to set the time yourself, nginx will check the file modification date.
etag is a tag that will be marked when updating static files. It is a string of strings generated by nginx's own algorithm. It looks like this

etag:“50b1c1d4f775c61:df3”

Etag is an optimization supplement to Last-Modified by http version iteration, mainly to solve:

  • Some files may be changed periodically, but their content does not change (only the modification time of the change), at this time we do not want the client to think that the file has been modified, and re-GET;
  • Some files are modified very frequently, such as modification within seconds (for example, N times within 1 second), the granularity that If-Modified-Since can check is s level, and this modification cannot be judged (or Say that UNIX records MTIME can only be accurate to seconds);
  • Some servers cannot accurately get the last modification time of the file.

If Last-Modified doesn't work, try turning on Etag

priority

Because the priority of the strong cache is higher than that of the negotiated cache, there are the following attribute priority relationships

Cache-Control > expires > Last-Modified|etag

When the server receives the request, it will first judge the last-modified of the resource, and then judge the etag, which must not expire before returning 304, so they are effective at the same time

Summarize

Nginx is generally configured for operation and maintenance, and the meta on html needs to be manually added by front-end students. So once there is a problem with the cache, you can go to see if the cache is set in the html, and then ask the operation and maintenance colleagues to see what the relevant configuration of nginx is.

Appendix Cache attribute value description

The meta in html has the same value as the header attribute of the server, here is an addition to avoid having to flip through the document when using it

Cache-Control

  • Public indicates that the response can be cached by any cache.
  • Private indicates that the entire or partial response message for a single user cannot be processed by the shared cache. This allows the server to describe only a partial response message for a user that is not valid for other users' requests.
  • no-cache indicates that the request or response message cannot be cached
  • no-store is used to prevent important information from being released unintentionally. Sending it in a request message will cause neither the request nor the response message to use the cache.
  • max-age indicates that the client can receive responses whose lifetime is no longer than the specified time (in seconds).
  • min-fresh indicates that the client can receive responses with a response time less than the current time plus the specified time.
  • max-stale indicates that the client can receive response messages beyond the timeout period. If you specify a value for max-stale messages, the client can receive response messages that exceed the value specified for the timeout period.

Last-Modified/If-Modified-Since

  • Last-Modified/If-Modified-Since should be used in conjunction with Cache-Control.
  • Last-Modified: Indicates the last modification time of this response resource. When the web server responds to the request, it tells the browser when the resource was last modified.
  • If-Modified-Since: When the resource expires (using the max-age identified by Cache-Control), it is found that the resource has a Last-Modified statement, and the header If-Modified-Since is added to the web server again to indicate the request time. After receiving the request, the web server finds that there is a header If-Modified-Since and compares it with the last modification time of the requested resource. If the last modification time is relatively new, indicating that the resource has been modified again, respond to the entire resource content (written in the response message body), HTTP 200; if the last modification time is relatively old, indicating that the resource has no new modification, respond to HTTP 304, Tell the browser to continue using the saved cache.

expires

  • -1 means that it has expired 1 second ago
  • max is usually understood as never invalid (the official website document is actually "Thu, 31 Dec 2037 23:55:55 GMT")
  • 1d and 1M refer to the specific time of 1 day and 1 month (Configuration file measurement units on the official website)

Guess you like

Origin blog.csdn.net/qq_38217940/article/details/125349105