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文件的名称上,然后当进行更改时,增加脚本上的版本并更新所有引用。这肯定可以完成工作,但是在每个版本上更新引用可能会很麻烦。

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


当前回答

<script>  
  var version = new Date().getTime();  
  var script = document.createElement("script");  
  script.src = "app.js?=" + version;  
  document.body.appendChild(script);  
</script>

如果有人已经把它贴在上面过多的答案中,请随意删除。

其他回答

一个简单的方法。 编辑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]

谷歌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。当您更改版本时,客户端浏览器将更新新文件。

并非所有浏览器都使用'?’在里面。我所做的是确保它被尽可能多地缓存,我将版本包含在文件名中。

而不是stuff。js?我用stuff_123.js

我使用mod_redirect(我认为)在apache有stuff_*.js去stuff.js

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

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

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

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

你可以用.htaccess来实现

在你的.htaccess文件中添加以下代码行:

# DISABLE CACHING
<IfModule mod_headers.c>
  <FilesMatch "\.js$">
      Header set Cache-Control "no-store, max-age=0"
  </FilesMatch>
</IfModule>