强制浏览器清除缓存
有没有办法在我的页面上放置一些代码,以便当有人访问网站时,它会清除浏览器缓存,以便他们可以查看更改?
使用的语言:ASP.NET、VB.NET,当然还有 HTML、CSS 和 jQuery。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
如果这是关于
.css
和.js
更改,那么一种方法是通过在文件中附加“_versionNo
”之类的内容来“缓存清除”每个版本的名称。例如:或在文件名之后:
您可以检查此链接到看看它是如何运作的。
If this is about
.css
and.js
changes, then one way is "cache busting" by appending something like "_versionNo
" to the file name for each release. For example:or after the file name:
You can check this link to see how it could work.
查看 缓存控制 和 cache-control 。 i18nguy.com/markup/metatags.html" rel="noreferrer">过期 META 标记。
另一种常见做法是将不断变化的字符串附加到请求的末尾文件。例如:
Look into the cache-control and the expires META Tag.
<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>
2012 更新
这是一个老问题,但我认为它需要更新的答案,因为现在有一种方法可以更好地控制网站缓存。
在 离线 Web 应用程序(实际上是任何 HTML5 网站)
applicationCache.swapCache()
可用于更新缓存您网站的版本,无需手动重新加载页面。这是来自 HTML5 Rocks 上使用应用程序缓存初学者指南的代码示例,解释了如何更新用户访问您网站的最新版本:
另请参阅 Mozilla 开发者网络上的使用应用程序缓存更多信息。
2016 年更新
网络上的事物变化很快。
这个问题是在 2009 年提出的,2012 年我发布了关于处理问题中描述的问题的新方法的更新。又四年过去了,现在看来它已经被弃用了。感谢cgaldiolo在评论中指出这一点。
目前,截至 2016 年 7 月,HTML 标准第 7.9 节,离线 Web 应用程序 包含弃用警告:
我在 2012 年引用的 Mozilla 开发者网络上的 使用应用程序缓存也是如此:
另请参阅错误 1204581 - 如果启用了服务工作线程获取拦截,则为 AppCache 添加弃用通知。
Update 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.This is a code example from the Beginner's Guide to Using the Application Cache on HTML5 Rocks explaining how to update users to the newest version of your site:
See also Using the application cache on Mozilla Developer Network for more info.
Update 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 cgaldiolo for pointing it out in the comments.
Currently, as of July 2016, the HTML Standard, Section 7.9, Offline Web applications includes a deprecation warning:
So does Using the application cache on Mozilla Developer Network that I referenced in 2012:
See also Bug 1204581 - Add a deprecation notice for AppCache if service worker fetch interception is enabled.
不是这样的。一种方法是在传送内容时发送适当的标头以强制浏览器重新加载:
确保网页不会在所有浏览器中被缓存。
如果您在 SO 上搜索
“缓存标头”
或类似内容,您将查找 ASP.NET 的具体示例。如果您无法控制服务器端的标头,另一种不太干净但有时唯一的方法是向正在调用的资源添加随机 GET 参数:
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.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:
我遇到了类似的问题,这就是我解决它的方法:
在
index.html
文件中我添加了清单:在
部分中包含更新缓存的脚本:
在
部分我插入了onload函数:
在
cache.manifest
中,我放置了我想要的所有文件缓存。现在重要的是,它在我的情况(Apache)中只需更新每次“版本”注释即可工作。还可以选择使用“?ver=001”或名称末尾的其他内容来命名文件,但不需要。仅更改# version 1.01
就会触发缓存更新事件。在 index.html 中仅包含 1.、2. 和 3. 点非常重要。否则
发生的原因是每个“子”文件都试图在页面已经缓存的情况下缓存该页面。
在
update_cache.js
文件中,我放置了以下代码:现在您只需更改文件,并在清单中更新版本注释。现在访问index.html页面将更新缓存。
解决方案的各个部分不是我的,但我通过互联网找到了它们并将它们组合在一起,以便它可以工作。
I had similiar problem and this is how I solved it:
In
index.html
file I've added manifest:In
<head>
section included script updating the cache:In
<body>
section I've inserted onload function: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.It's important to include 1., 2. and 3. points only in index.html. Otherwise
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:Now you just change files and in manifest you have to update version comment. Now visiting index.html page will update the cache.
The parts of solution aren't mine but I've found them through internet and put together so that it works.
对于静态资源,正确的缓存是使用查询参数以及每个部署或文件版本的值。这将在每次部署后清除缓存。
这是 ASP.NET MVC 示例。
不要忘记更新程序集版本。
For static resources right caching would be to use query parameters with value of each deployment or file version. This will have effect of clearing cache after each deployment.
Here is ASP.NET MVC example.
Don't forget to update assembly version.
2023 年起
在撰写本文时,大多数主流 Web 浏览器(Safari 除外)都支持
Clear-Site-Data
HTTP 标头 [MDN 参考]。要指示客户端 Web 浏览器清除网站域和子域的浏览器缓存,请在服务器的 HTTP 响应中设置以下标头:
或者,以下标头可能会更好地跨浏览器支持,但它会清除其他网站数据,例如除了浏览器缓存之外,还有 localStorage 和 cookies。
2023 onward
At the time of writing, most mainstream web browsers (except Safari) support the
Clear-Site-Data
HTTP header [MDN reference].To instruct a client web browser to clear the browser cache for the website's domain and subdomains, set the following header in the HTTP response from the server:
Alternatively, the following header may be better supported across browsers, but it clears other website data, such as localStorage and cookies, in addition to the browser cache.
我有一个案例,我会在线拍摄客户的照片,如果照片发生更改,则需要更新 div。浏览器仍然显示旧照片。所以我使用了调用随机 GET 变量的技巧,该变量每次都是唯一的。这是如果它可以帮助任何人
编辑
正如其他人指出的那样,以下是更有效的解决方案,因为它仅在图像发生更改时才会重新加载图像,并通过文件大小识别此更改:
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
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:
很多答案都没有抓住要点——大多数开发人员都清楚关闭缓存效率低下。然而,在许多常见情况下,效率并不重要,并且默认缓存行为被严重破坏。
其中包括嵌套的迭代脚本测试(最重要的!)和损坏的第三方软件解决方法。此处给出的解决方案都不足以解决此类常见情况。大多数网络浏览器的缓存过于激进,并且没有提供避免这些问题的明智方法。
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.
将 URL 更新为以下内容对我来说很有效:
/custom.js?id=1
通过在
?id=
后面添加唯一的数字并针对新更改递增该数字,用户可以不必按CTRL + F5
来刷新缓存。或者,您可以在?id=
之后附加当前时间或 Epoch 的哈希或字符串版本,例如
?id=1520606295
Updating the URL to the following works for me:
/custom.js?id=1
By adding a unique number after
?id=
and incrementing it for new changes, users do not have to pressCTRL + F5
to refresh the cache. Alternatively, you can append hash or string version of the current time or Epoch after?id=
Something like
?id=1520606295
另请参阅 https://stackoverflow .com/questions/126772/how-to-force-a-web-browser-not-to-cache-images
Also see https://stackoverflow.com/questions/126772/how-to-force-a-web-browser-not-to-cache-images
这里是有关在 ASP.NET 中设置缓存的 MDSN 页面。
Here is the MDSN page on setting caching in ASP.NET.
不确定这是否真的对您有帮助,但这就是缓存在任何浏览器上的工作方式。当浏览器请求文件时,它应该始终向服务器发送请求,除非有“离线”模式。服务器将读取一些参数,例如修改日期或 etag。
服务器将返回 NOT MODIFIED 的 304 错误响应,浏览器将不得不使用其缓存。如果 etag 未在服务器端验证或修改日期低于当前修改日期,则服务器应返回带有新修改日期或 etag 或两者的新内容。
如果没有缓存数据发送到浏览器,我猜行为是不确定的,浏览器可能会也可能不会缓存不告诉它们如何缓存的文件。如果您在响应中设置缓存参数,它将正确缓存您的文件,然后服务器可能会选择返回 304 错误或新内容。
应该这样做。在 url 中使用随机参数或版本号更像是一种黑客行为。
http://www.checkupdown.com/status/E304.html
http://en.wikipedia.org/wiki/HTTP_ETag
http://www.xpertdeveloper。 com/2011/03/last-modified-header-vs-expire-header-vs-etag/
阅读后我发现还有一个过期日期。如果您遇到问题,可能是您设置了过期日期。换句话说,当浏览器缓存您的文件时,由于它有一个到期日期,因此不必在该日期之前再次请求它。换句话说,它永远不会向服务器询问该文件,也永远不会收到未修改的 304。它将简单地使用缓存,直到达到到期日期或缓存被清除。
所以这是我的猜测,你有某种到期日期,你应该使用最后修改的 etag 或所有这些的混合,并确保没有到期日期。
如果人们倾向于频繁刷新并且文件不会发生大量更改,那么设置一个较大的到期日期可能是明智的。
我的2分钱!
Not sure if that might really help you but that's how caching should work on any browser. When the browser request a file, it should always send a request to the server unless there is a "offline" mode. The server will read some parameters like date modified or etags.
The server will return a 304 error response for NOT MODIFIED and the browser will have to use its cache. If the etag doesn't validate on server side or the modified date is below the current modified date, the server should return the new content with the new modified date or etags or both.
If there is no caching data sent to the browser, I guess the behavior is undetermined, the browser may or may not cache file that don't tell how they are cached. If you set caching parameters in the response it will cache your files correctly and the server then may choose to return a 304 error, or the new content.
This is how it should be done. Using random params or version number in urls is more like a hack than anything.
http://www.checkupdown.com/status/E304.html
http://en.wikipedia.org/wiki/HTTP_ETag
http://www.xpertdeveloper.com/2011/03/last-modified-header-vs-expire-header-vs-etag/
After reading I saw that there is also a expire date. If you have problem, it might be that you have a expire date set up. In other words, when the browser will cache your file, since it has a expiry date, it shouldn't have to request it again before that date. In other words, it will never ask the file to the server and will never receive a 304 not modified. It will simply use the cache until the expiry date is reached or cache is cleared.
So that is my guess, you have some sort of expiry date and you should use last-modified etags or a mix of it all and make sure that there is no expire date.
If people tends to refresh a lot and the file doesn't get changed a lot, then it might be wise to set a big expiry date.
My 2 cents!
我实现了这个适合我的简单解决方案(尚未在生产环境中):
我有一个小文件位于html所在的位置:
“versio.txt”:
在我的所有页面中都会调用此函数,因此在加载时会检查如果 localStorage 的版本值低于当前版本,并执行
...强制从服务器而不是从缓存重新加载。
(显然,您可以使用 cookie 或其他持久客户端存储来代替 localStorage)
我选择此解决方案是因为它简单,因为仅维护单个文件“versio.txt”将强制重新加载整个站点。
queryString 方法很难实现,而且也会被缓存(如果从 v1.1 更改为以前的版本将从缓存加载,那么这意味着缓存不会刷新,将所有以前的版本保留在缓存中)。
我是一个小新手,非常感谢您的专业检查和指导。检查以确保我的方法是一个好的方法。
希望有帮助。
I implemented this simple solution that works for me (not yet on production environment):
I've a little file located where the html are:
"versio.txt":
This function is called in all of my pages, so when loading it checks if the localStorage's version value is lower than the current version and does a
...to force reload from server instead from cache.
(obviously, instead of localStorage you can use cookies or other persistent client storage)
I opted for this solution for its simplicity, because only mantaining a single file "versio.txt" will force the full site to reload.
The queryString method is hard to implement and is also cached (if you change from v1.1 to a previous version will load from cache, then it means that the cache is not flushed, keeping all previous versions at cache).
I'm a little newbie and I'd apreciate your professional check & review to ensure my method is a good approach.
Hope it helps.
有一个可以使用的技巧。该技巧是将参数/字符串附加到脚本标记中的文件名,并在文件更改时更改它。
浏览器将整个字符串解释为文件路径,即使“?”后面的内容也是如此。是参数。所以现在发生的情况是,下次更新文件时,只需更改网站上脚本标记中的数字(示例
There is one trick that can be used.The trick is to append a parameter/string to the file name in the script tag and change it when you file changes.
<script src="myfile.js?version=1.0.0"></script>
The browser interprets the whole string as the file path even though what comes after the "?" are parameters. So wat happens now is that next time when you update your file just change the number in the script tag on your website (Example
<script src="myfile.js?version=1.0.1"></script>
) and each users browser will see the file has changed and grab a new copy.在workers js中
,然后在标题代码中添加this js变量。`
最后添加此页脚代码
in workers js
then add your this js variable in your header code.`
at last add this footer code
除了设置 Cache-control: no-cache 之外,如果您希望每次都刷新本地副本,还应该将 Expires 标头设置为 -1(某些版本的 IE 似乎需要这样做)。
请参阅 HTTP 缓存 - 检查服务器,始终发送 If-Modified-Since
In addition to setting Cache-control: no-cache, you should also set the Expires header to -1 if you would like the local copy to be refreshed each time (some versions of IE seem to require this).
See HTTP Cache - check with the server, always sending If-Modified-Since
强制浏览器清除缓存或重新加载正确的数据?我已经尝试了 stackoverflow 中描述的大多数解决方案,有些有效,但过了一会儿,它最终会缓存并显示以前加载的脚本或文件。是否有另一种方法可以清除缓存(css、js 等)并在所有浏览器上实际工作?
到目前为止,我发现如果您更改服务器上文件的日期和时间,可以单独重新加载特定资源。 “清除缓存”并不像应有的那么容易。我意识到“触摸”缓存的服务器文件实际上会更改服务器上缓存的源文件的日期和时间(在 Edge、Chrome 和 Firefox 上测试),而不是清除浏览器上的缓存,并且大多数浏览器会自动下载最多的文件服务器上内容的最新副本(代码、图形以及多媒体)。我建议您在程序运行之前复制服务器上最新的脚本和“执行触摸操作”解决方案,这样它会将所有问题文件的日期更改为最新的日期和时间,然后它会下载一个新的副本到您的浏览器:
然后...程序的其余部分...
我花了一些时间来解决这个问题(因为许多浏览器对不同命令的行为不同,但它们都会检查文件的时间和与您在浏览器中下载的副本进行比较,如果日期和时间不同,则会进行刷新),如果您不能按照假定的正确方式进行操作,那么总有另一个可用且更好的解决方案。致以最诚挚的问候,祝露营愉快。顺便说一下触摸();或者替代方案适用于许多编程语言,包括 javascript bash sh php,您可以在 html 中包含或调用它们。
Force browsers to clear cache or reload correct data? I have tried most of the solutions described in stackoverflow, some work, but after a little while, it does cache eventually and display the previous loaded script or file. Is there another way that would clear the cache (css, js, etc) and actually work on all browsers?
I found so far that specific resources can be reloaded individually if you change the date and time on your files on the server. "Clearing cache" is not as easy as it should be. Instead of clearing cache on my browsers, I realized that "touching" the server files cached will actually change the date and time of the source file cached on the server (Tested on Edge, Chrome and Firefox) and most browsers will automatically download the most current fresh copy of whats on your server (code, graphics any multimedia too). I suggest you just copy the most current scripts on the server and "do the touch thing" solution before your program runs, so it will change the date of all your problem files to a most current date and time, then it downloads a fresh copy to your browser:
then ... the rest of your program...
It took me some time to resolve this issue (as many browsers act differently to different commands, but they all check time of files and compare to your downloaded copy in your browser, if different date and time, will do the refresh), If you can't go the supposed right way, there is always another usable and better solution to it. Best Regards and happy camping. By the way touch(); or alternatives work in many programming languages inclusive in javascript bash sh php and you can include or call them in html.
对于 webpack 用户:-
我在 webpack 配置中添加了 chunkhash 时间。这解决了我在每次部署时使缓存失效的问题。此外,我们还需要注意,index.html/ asset.manifest 不会同时缓存在您的 CDN 或浏览器中。 webpack 配置中块名称的配置将如下所示:-
fileName: [chunkhash]-${Date.now()}.js
或如果您使用 contenthash 那么
fileName: [contenthash]-${Date.now()} .js
For webpack users:-
I added time with chunkhash in my webpack config. This solved my problem of invalidating cache on each deployment. Also we need to take care that index.html/ asset.manifest is not cached both in your CDN or browser. Config of chunk name in webpack config will look like this:-
fileName: [chunkhash]-${Date.now()}.js
or If you are using contenthash then
fileName: [contenthash]-${Date.now()}.js
这是我使用 PHP 在我的一个应用程序中解决的简单解决方案。
所有 JS 和 CSS 文件都放置在带有版本名称的文件夹中。示例:“1.0.01”
创建了一个 Helper 并在那里定义了版本号
以及链接的 JS 和 SCC 文件,如下所示
每当我对任何 JS 或 CSS 文件进行更改时,我都会更改 Helper 中的系统版本并重命名该文件夹并部署它。
This is the simple solution I used to solve in one of my applications using PHP.
All JS and CSS files are placed in a folder with version name. Example : "1.0.01"
Created a Helper and Defined the version Number there
And Linked JS and SCC Files like below
Whenever I make changes to any JS or CSS file, I change the System Verson in Helper and rename the folder and deploy it.
我遇到了同样的问题,我所做的就是更改链接到我的index.html 文件的文件名,然后进入index.html 文件并更新它们的名称,这不是最佳实践,但如果它有效,它就有效。浏览器将它们视为新文件,因此它们会重新下载到用户设备上。
例子:
我想更新一个css文件,其名为styles.css,将其更改为styless.css
进入index.html并更新,并将其更改为
I had the same problem, all i did was change the file names which are linked to my index.html file and then went into the index.html file and updated their names, not the best practice but if it works it works. The browser sees them as new files so they get redownloaded on to the users device.
example:
I want to update a css file, its named styles.css, change it to styless.css
Go into index.html and update , and change it to
如果有兴趣,我找到了让浏览器在 .NET MVC (.net fw 4.8) 和使用捆绑包的上下文中刷新 .css 和 .js 的解决方案。
我想让浏览器仅在部署新程序集后刷新缓存文件。
根据 Paulius Zaliaduonis 的响应,我的解决方案如下:
这是代码,
您将获得标签,就像
您只需要记住在部署之前构建新版本一样。
再见
in case interested I've found my solution to get browsers refreshing .css and .js in the context of .NET MVC (.net fw 4.8) and the use of bundles.
I wanted to make browsers refresh cached files only after a new assembly is deployed.
Buinding on Paulius Zaliaduonis response, my solution is as follows:
Here is the code
You'll get tags like
you just need to remember to to build a new version before deploying.
Ciao
您想清除缓存,还是只是确保当前(已更改?)页面未被缓存?
如果是后者,应该很简单
Do you want to clear the cache, or just make sure your current (changed?) page is not cached?
If the latter, it should be as simple as