Html 强制浏览器清除缓存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1922910/
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
Force browser to clear cache
提问by Adam
Is there a way I can put some code on my page so when someone visits a site, it clears the browser cache, so they can view the changes?
有没有办法可以在我的页面上放置一些代码,以便当有人访问网站时,它会清除浏览器缓存,以便他们可以查看更改?
Languages used: ASP.NET, VB.NET, and of course HTML, CSS, and jQuery.
使用的语言:ASP.NET、VB.NET,当然还有 HTML、CSS 和 jQuery。
回答by Fermin
If this is about .css
and .js
changes, one way is to to "cache busting" is by appending something like "_versionNo
" to the file name for each release. For example:
如果这是关于.css
并.js
更改,一种方法是“缓存破坏”是通过_versionNo
在每个版本的文件名后附加类似“ ”的内容。例如:
script_1.0.css // This is the URL for release 1.0
script_1.1.css // This is the URL for release 1.1
script_1.2.css // etc.
Or alternatively do it after the file name:
或者在文件名之后执行:
script.css?v=1.0 // This is the URL for release 1.0
script.css?v=1.1 // This is the URL for release 1.1
script.css?v=1.2 // etc.
You can check out this linkto see how it could work.
您可以查看此链接以了解它是如何工作的。
回答by Sampson
Look into the cache-controland the expiresMETA Tag.
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="EXPIRES" CONTENT="Mon, 22 Jul 2002 11:12:01 GMT">
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="EXPIRES" CONTENT="Mon, 22 Jul 2002 11:12:01 GMT">
Another common practices is to append constantly-changing strings to the end of the requested files. For instance:
另一种常见做法是将不断变化的字符串附加到请求文件的末尾。例如:
<script type="text/javascript" src="main.js?v=12392823"></script>
<script type="text/javascript" src="main.js?v=12392823"></script>
回答by rsp
Update 2012
2012 年更新
This is an old question but I think it needs a more up to date answer because now there is a way to have more control of website caching.
这是一个老问题,但我认为它需要一个更新的答案,因为现在有一种方法可以更好地控制网站缓存。
In Offline Web Applications(which is really any HTML5 website) applicationCache.swapCache()
can be used to update the cached version of your website without the need for manually reloading the page.
在离线 Web 应用程序(实际上是任何 HTML5 网站)applicationCache.swapCache()
可用于更新网站的缓存版本,而无需手动重新加载页面。
This is a code example from the Beginner's Guide to Using the Application Cacheon HTML5 Rocks explaining how to update users to the newest version of your site:
这是在 HTML5 Rocks 上使用应用程序缓存的初学者指南中的代码示例,解释了如何将用户更新到您网站的最新版本:
// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new hotness.
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {
// Manifest didn't changed. Nothing new to server.
}
}, false);
}, false);
See also Using the application cacheon Mozilla Developer Network for more info.
另请参阅在 Mozilla 开发人员网络上使用应用程序缓存以获取更多信息。
Update 2016
2016 年更新
Things change quickly on the Web. This question was asked in 2009 and in 2012 I posted an update about a new way to handle the problem described in the question. Another 4 years passed and now it seems that it is already deprecated. Thanks to cgaldiolofor pointing it out in the comments.
Web 上的事情变化很快。这个问题是在 2009 年提出的,2012 年我发布了关于处理问题中描述的问题的新方法的更新。又过了 4 年,现在它似乎已经被弃用了。感谢cgaldiolo在评论中指出。
Currently, as of July 2016, the HTML Standard, Section 7.9, Offline Web applicationsincludes a deprecation warning:
目前,截至 2016 年 7 月,HTML 标准第 7.9 节,离线 Web 应用程序包含弃用警告:
This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using any of the offline Web application features at this time is highly discouraged. Use service workers instead.
此功能正在从 Web 平台中删除。(这是一个需要很多年的漫长过程。)此时强烈建议不要使用任何离线 Web 应用程序功能。改用服务工作者。
So does Using the application cacheon Mozilla Developer Network that I referenced in 2012:
我在 2012 年提到的使用Mozilla Developer Network 上的应用程序缓存也是如此:
Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
已弃用
此功能已从 Web 标准中删除。虽然一些浏览器可能仍然支持它,但它正在被删除。不要在旧项目或新项目中使用它。使用它的页面或 Web 应用程序可能随时中断。
See also Bug 1204581 - Add a deprecation notice for AppCache if service worker fetch interception is enabled.
另请参阅错误 1204581 - 如果启用了 Service Worker fetch 拦截,则为 AppCache 添加弃用通知。
回答by Pekka
Not as such. One method is to send the appropriate headers when delivering content to force the browser to reload:
不是这样。一种方法是在传递内容时发送适当的标头以强制浏览器重新加载:
Making sure a web page is not cached, across all browsers.
If your search for "cache header"
or something similar here on SO, you'll find ASP.NET specific examples.
如果您"cache header"
在 SO 上搜索或类似的内容,您将找到 ASP.NET 特定示例。
Another, less clean but sometimes only way if you can't control the headers on server side, is adding a random GET parameter to the resource that is being called:
如果您无法控制服务器端的标头,另一种不太干净但有时唯一的方法是向正在调用的资源添加一个随机的 GET 参数:
myimage.gif?random=1923849839
回答by Paulius Zaliaduonis
For static resourcesright caching would be to use query parameterswith value of each deployment or file version. This will have effect of clearing cache after each deployment.
对于静态资源,正确缓存将使用具有每个部署或文件版本值的查询参数。这将具有在每次部署后清除缓存的效果。
/Content/css/Site.css?version={FileVersionNumber}
Here is ASP.NET MVC example.
这是 ASP.NET MVC 示例。
<link href="@Url.Content("~/Content/Css/Reset.css")[email protected]().Assembly.GetName().Version" rel="stylesheet" type="text/css" />
Don't forget to update assembly version.
不要忘记更新程序集版本。
回答by Wojtek Mazurek
I had similiar problem and this is how I solved it:
我遇到了类似的问题,这就是我解决它的方法:
In
index.html
file I've added manifest:<html manifest="cache.manifest">
In
<head>
section included script updating the cache:<script type="text/javascript" src="update_cache.js"></script>
In
<body>
section I've inserted onload function:<body onload="checkForUpdate()">
In
cache.manifest
I've put all files I want to cache. It is important now that it works in my case (Apache) just by updating each time the "version" comment. It is also an option to name files with "?ver=001" or something at the end of name but it's not needed. Changing just# version 1.01
triggers cache update event.CACHE MANIFEST # version 1.01 style.css imgs/logo.png #all other files
It's important to include 1., 2. and 3. points onlyin index.html. Otherwise
GET http://foo.bar/resource.ext net::ERR_FAILED
occurs because every "child" file tries to cache the page while the page is already cached.
In
update_cache.js
file I've put this code:function checkForUpdate() { if (window.applicationCache != undefined && window.applicationCache != null) { window.applicationCache.addEventListener('updateready', updateApplication); } } function updateApplication(event) { if (window.applicationCache.status != 4) return; window.applicationCache.removeEventListener('updateready', updateApplication); window.applicationCache.swapCache(); window.location.reload(); }
在
index.html
文件中,我添加了清单:<html manifest="cache.manifest">
在
<head>
部分包括更新缓存的脚本:<script type="text/javascript" src="update_cache.js"></script>
在
<body>
我插入了 onload 函数的部分:<body onload="checkForUpdate()">
在
cache.manifest
我已经把我想要缓存的所有文件。现在很重要的是,它在我的情况下(Apache)只需在每次“版本”注释时更新即可。也可以选择使用“?ver=001”或名称末尾的内容命名文件,但不需要。更改只会# version 1.01
触发缓存更新事件。CACHE MANIFEST # version 1.01 style.css imgs/logo.png #all other files
仅在 index.html 中包含 1.、2. 和 3. 点很重要。除此以外
GET http://foo.bar/resource.ext net::ERR_FAILED
发生的原因是每个“子”文件都在页面已经缓存时尝试缓存页面。
在
update_cache.js
文件中我放了这段代码:function checkForUpdate() { if (window.applicationCache != undefined && window.applicationCache != null) { window.applicationCache.addEventListener('updateready', updateApplication); } } function updateApplication(event) { if (window.applicationCache.status != 4) return; window.applicationCache.removeEventListener('updateready', updateApplication); window.applicationCache.swapCache(); window.location.reload(); }
Now you just change files and in manifest you have to update version comment. Now visiting index.html page will update the cache.
现在您只需更改文件,并且在清单中您必须更新版本注释。现在访问 index.html 页面将更新缓存。
The parts of solution aren't mine but I've found them through internet and put together so that it works.
解决方案的部分不是我的,但我通过互联网找到了它们并将它们放在一起以使其有效。
回答by zeeshan
I had a case where I would take photos of clients online and would need to update the div if a photo is changed. Browser was still showing the old photo. So I used the hack of calling a random GET variable, which would be unique every time. Here it is if it could help anybody
我有一个案例,我会在网上为客户拍照,如果照片更改,则需要更新 div。浏览器仍然显示旧照片。所以我使用了调用随机 GET 变量的技巧,它每次都是唯一的。这是如果它可以帮助任何人
<img src="/photos/userid_73.jpg?random=<?php echo rand() ?>" ...
EDIT As pointed out by others, following is much more efficient solution since it will reload images only when they are changed, identifying this change by the file size:
编辑正如其他人所指出的,以下是更有效的解决方案,因为它只会在更改图像时重新加载图像,并通过文件大小识别此更改:
<img src="/photos/userid_73.jpg?modified=<? filemtime("/photos/userid_73.jpg")?>"
回答by John
A lot of answers are missing the point - most developers are well aware that turning off the cache is inefficient. However, there are many common circumstances where efficiency is unimportant and default cache behavior is badly broken.
很多答案都没有抓住重点 - 大多数开发人员都清楚关闭缓存效率低下。但是,在许多常见情况下,效率并不重要并且默认缓存行为被严重破坏。
These include nested, iterative script testing (the big one!) and broken third party software workarounds. None of the solutions given here are adequate to address such common scenarios. Most web browsers are far too aggressive caching and provide no sensible means to avoid these problems.
这些包括嵌套的、迭代的脚本测试(最重要的!)和损坏的第三方软件解决方法。此处给出的解决方案均不足以解决此类常见情况。大多数 Web 浏览器的缓存过于激进,并且没有提供避免这些问题的合理方法。
回答by nPcomp
Updating the URL to the following works for me:
将 URL 更新为以下内容对我有用:
/custom.js?id=1
/custom.js?id=1
By adding a unique number after ?id=
and incrementing it for new changes, users do not have to press CTRL + F5
to refresh the cache. Alternatively, you can append hash or string version of the current time or Epoch after ?id=
通过在之后添加一个唯一编号?id=
并为新更改增加它,用户不必按CTRL + F5
刷新缓存。或者,您可以在之后附加当前时间或纪元的哈希或字符串版本?id=
Something like ?id=1520606295
就像是 ?id=1520606295
回答by S Pangborn
<meta http-equiv="pragma" content="no-cache" />
Also see https://stackoverflow.com/questions/126772/how-to-force-a-web-browser-not-to-cache-images
另请参阅https://stackoverflow.com/questions/126772/how-to-force-a-web-browser-not-to-cache-images