使静态资源的浏览器缓存失效

发布于 2024-12-16 17:14:32 字数 174 浏览 6 评论 0原文

我正在研究静态资源的缓存。通常,当脚本或样式发生更改时,它会给人们带来一段时间的问题,直到他们的浏览器决定是时候使我们的文件缓存无效。

我希望通过在所有脚本和样式标签的末尾插入一个值来强制浏览器向服务器发送实际请求来解决这个问题。该值应该在多个服务器上保持不变,直到发出命令来更改它。如何在多个服务器上生成/更改此值?

I'm working on caching of static resources. Often when a script or style is changed, it will cause problems for people for a while until their browser decides that it is time to invalidate its cache of our file.

I am hoping to solve this problem by inserting a value on the end of all script and style tags to force the browsers to send an actual request to the server. This value should stay the same across multiple servers until a command is issued to change it. How can I generate/change this value across multiple servers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾`听者〃 2024-12-23 17:14:32

您可以通过查询字符串或文件名更改来修改静态资源。任一方法都应在客户端上刷新。

1.查询字符串 revving - 对“style.css”的引用变为“style.css?v=1.0”

2. filename revving - 对“style.css”的引用变成“style-1.0.css”(还必须在服务器上重命名或创建文件“style-1.0.css”)

我使用了这两种方法,querystring可能更常见,因为您不必重命名服务器上的文件。

然而,这篇文章,Revving 文件名:don不使用查询字符串,给出了使用文件名加速的充分理由


实现查询字符串加速的一种方法是在 web.config 应用程序设置中存储版本号

<appSettings>
    <add key="staticResourceVersion" value="1.1"/>
    ...
</appSettings>

然后创建一些实用方法(或直接调用 ConfigurationManager.AppSettings)使用内联静态资源标记,例如:

<link rel="stylesheet" type="text/css" 
    href="/css/style.css?v=<%=Utilities.GetStaticResourceVersion() %>" />
<script type="text/javascript"
    src="/js/script.js?v=<%=Utilities.GetStaticResourceVersion() %>"></script>

you can revise static resources with a querystring or filename change. Either method should refresh on the client.

1. querystring revving - references to "style.css" become "style.css?v=1.0"

2. filename revving - references to "style.css" become "style-1.0.css" (have to also rename or create the file "style-1.0.css" on your server)

I've used both methods, querystring is probably more common because you don't have to rename the file on the server.

However, this write up, Revving Filenames: don’t use querystring, gives a good reason to use filename revving instead


One way to implement this for querystring revving would be to store a version number in the web.config app settings

<appSettings>
    <add key="staticResourceVersion" value="1.1"/>
    ...
</appSettings>

Then create some utility method (or call ConfigurationManager.AppSettings directly) to use inline for static resource markup, for example:

<link rel="stylesheet" type="text/css" 
    href="/css/style.css?v=<%=Utilities.GetStaticResourceVersion() %>" />
<script type="text/javascript"
    src="/js/script.js?v=<%=Utilities.GetStaticResourceVersion() %>"></script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文