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

其他回答

一种解决方案是在获取资源时,将包含时间戳的查询字符串附加到URL。这利用了浏览器不会缓存从包含查询字符串的url中获取的资源这一事实。

你可能不希望浏览器完全不缓存这些资源;更可能的情况是,您希望它们被缓存,但您希望浏览器在文件可用时获取该文件的新版本。

最常见的解决方案似乎是在文件名本身中嵌入时间戳或修订号。这是一个多一点的工作,因为你的代码需要修改请求正确的文件,但这意味着,例如版本7你的snazzy_javascript_file.js(即snazzy_javascript_file_7.js)被缓存在浏览器上,直到你发布版本8,然后你的代码改变获取snazzy_javascript_file_8.js。

虽然它是特定于框架的,但Django 1.4拥有staticfiles应用程序功能,其工作方式与上面答案中的“greenfelt”站点类似

jQuery函数getScript也可以用来确保每次页面加载时确实加载了js文件。

我是这样做的:

$(document).ready(function(){
    $.getScript("../data/playlist.js", function(data, textStatus, jqxhr){
         startProgram();
    });
});

请登录http://api.jquery.com/jQuery.getScript/查看该功能

默认情况下,$. getscript()将缓存设置设置为false。这将向请求URL附加一个带有时间戳的查询参数,以确保浏览器在每次请求脚本时都会下载脚本。

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

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

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