Home > Article > Web Front-end > How to avoid browser caching static files
How to prevent the browser from caching static resources? This article will introduce you to several methods to prevent browsers from caching static resources. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Why do you need to avoid browser caching?
Many scenarios at work need to avoid browser caching. For example: when we make changes to css, js, images, etc. and refresh the web page, it has no effect at all. This is because There is a reason for caching.
Therefore, when we may need to change js or css frequently, we need to prevent browsing from caching.
How to prevent browser cache from caching static files?
Let’s introduce the method to prevent the browser from caching:
1. If you want to disable caching when making a request, you can set the request header:
Cache-Control: no-cache, no-store, must-revalidate
2. Increase the version number
Add a version number to the requested resource. This is a common practice. For example:
<link rel="stylesheet" type="text/css" href="../css/style.css?version=1.8.9"/> <script type="text/javascript" src="../js/jquery.min.js?version=1.7.2" ></script>
The advantage of doing this is that it should be cached. When caching static files, you can freely control when to load and update the cache with the latest resources.
3. Use HTML to disable caching
HTML can also disable caching, that is, add a meta tag to the head tag of the page. Example:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
Note: Although caching can be disabled, only some browsers support it, and because the proxy does not parse HTML documents, the proxy server does not support this method.
4. Use random numbers
Let’s take a simple example to see how to use random numbers to avoid browser caching
// 方法一: document.write( " <script src='jquery.min.js?rnd= " + Math.random() + " '></s " + " cript> " ) // 方法二: var js = document.createElement( " script " ) js.src = " jquery.min.js " + Math.random() document.body.appendChild(js)
Note: As in the above example, if random numbers are used , the js file will never be cached and will have to be reloaded from the server every time, even if nothing changes.
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of How to avoid browser caching static files. For more information, please follow other related articles on the PHP Chinese website!