We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a ctrlF5 refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time.

我们目前的想法是简单地将版本号附加到JavaScript文件的名称上,然后当进行更改时,增加脚本上的版本并更新所有引用。这肯定可以完成工作,但是在每个版本上更新引用可能会很麻烦。

我确信我们不是第一个处理这个问题的人,我想我应该把它扔给社区。当你更新你的代码时,你如何确保客户端更新他们的缓存?如果您正在使用上面描述的方法,那么您使用的是简化更改的过程吗?


当前回答

将当前时间附加到URL确实是一种常见的解决方案。但是,如果你愿意,你也可以在web服务器级别管理它。服务器可以配置为javascript文件发送不同的HTTP头。

例如,要强制文件缓存不超过1天,你可以发送:

Cache-Control: max-age=86400, must-revalidate

对于测试版,如果你想强迫用户总是获得最新的,你可以使用:

Cache-Control: no-cache, must-revalidate

其他回答

我的同事刚刚在http://www.stefanhayden.com/blog/2006/04/03/css-caching-hack/上发布了这个方法(参考css)。很高兴看到其他人在使用它,而且它似乎很有效。我假设在这一点上,没有更好的方法比查找-替换增量这些“版本号”在所有的脚本标签?

谷歌Page-Speed:不要在静态资源的URL中包含查询字符串。 大多数代理,尤其是Squid到3.0版本,不会缓存URL中带有"?"的资源,即使响应中存在cache -control: public报头。要为这些资源启用代理缓存,请从静态资源引用中删除查询字符串,并将参数编码到文件名本身中。

在这种情况下,您可以将版本包含到URL ex: http://abc.com/v1.2/script.js中,并使用apache mod_rewrite将链接重定向到http://abc.com/script.js。当您更改版本时,客户端浏览器将更新新文件。

一个简单的方法。 编辑htaccess

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} \.(jpe?g|bmp|png|gif|css|js|mp3|ogg)$ [NC]
RewriteCond %{QUERY_STRING} !^(.+?&v33|)v=33[^&]*(?:&(.*)|)$ [NC]
RewriteRule ^ %{REQUEST_URI}?v=33 [R=301,L]

一个简单的技巧,我可以很好地防止新旧javascript文件之间的冲突。这意味着:如果出现冲突和错误,将提示用户按Ctrl-F5。

在页面顶部添加如下内容

<h1 id="welcome"> Welcome to this page <span style="color:red">... press Ctrl-F5</span></h1>

看起来像

让这一行javascript作为加载页面时最后执行的代码:

document.getElementById("welcome").innerHTML = "Welcome to this page"

如果没有发生错误,上面的欢迎问候语几乎不可见,几乎立即被替换为

如何添加文件大小作为加载参数?

<script type='text/javascript' src='path/to/file/mylibrary.js?filever=<?=filesize('path/to/file/mylibrary.js')?>'></script>

因此,每次更新文件时,“filever”参数都会改变。

当您更新文件并且您的更新结果是相同的文件大小时,情况会如何?几率有多大?