如何防止缓存我的 Javascript 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7413234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to prevent caching of my Javascript file?
提问by Bdfy
I have a simple html:
我有一个简单的 html:
<html>
<body>
<head>
<meta charset="utf-8">
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
<script src="test.js"></script>
</body>
</html>
In test.js I changed a Javascript function, but my browser is caching this file. How to disable cache for script src?
在 test.js 中,我更改了一个 Javascript 函数,但我的浏览器正在缓存此文件。如何禁用脚本 src 的缓存?
回答by Curt
Add a random query string to the src
将随机查询字符串添加到 src
You could either do this manually by incrementing the querystring each time you make a change:
您可以通过每次更改时增加查询字符串来手动执行此操作:
<script src="test.js?version=1"></script>
Or if you are using a server side language, you could automatically generate this:
或者,如果您使用的是服务器端语言,则可以自动生成:
ASP.NET:
ASP.NET:
<script src="test.js?rndstr=<%= getRandomStr() %>"></script>
More info on cache-busting can be found here:
可以在此处找到有关缓存破坏的更多信息:
https://curtistimson.co.uk/post/front-end-dev/what-is-cache-busting/
https://curtistimson.co.uk/post/front-end-dev/what-is-cache-busting/
回答by Alex Pliutau
<script src="test.js?random=<?php echo uniqid(); ?>"></script>
EDIT: Or you could use the file modification time so that it's cached on the client.
编辑:或者您可以使用文件修改时间,以便将其缓存在客户端上。
<script src="test.js?random=<?php echo filemtime('test.js'); ?>"></script>
回答by Quentin
Configure your webserverto send caching control HTTP headers for the script.
配置您的网络服务器以发送脚本的缓存控制 HTTP 标头。
Fake headers in the HTML documents:
HTML 文档中的假标题:
- Aren't as well supported as real HTTP headers
- Apply to the HTML document, not to resources that it links to
- 不像真正的 HTTP 标头那样受支持
- 应用于 HTML 文档,而不是它链接到的资源
回答by daveoncode
You can append a queryString to your src and change it only when you will release an updated version:
您可以将 queryString 附加到您的 src 并仅在您发布更新版本时更改它:
<script src="test.js?v=1"></script>
In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)
这样,浏览器将使用缓存的版本,直到指定新版本(v=2,v=3...)
回答by Bas Slagter
You can add a random (or datetime string) as query string to the url that points to your script. Like so:
您可以将随机(或日期时间字符串)作为查询字符串添加到指向您的脚本的 url。像这样:
<script type="text/javascript" src="test.js?q=123"></script>
Every time you refresh the page you need to make sure the value of 'q' is changed.
每次刷新页面时,您都需要确保 'q' 的值已更改。