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

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


当前回答

如果您正在生成链接到JS文件的页面,一个简单的解决方案是将文件的最后修改时间戳附加到生成的链接。

这与Huppie的答案非常相似,但是可以在没有关键字替换的版本控制系统中工作。它也比附加当前时间要好,因为即使在文件完全没有更改的情况下,也可以防止缓存。

其他回答

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

在PHP中:

function latest_version($file_name){
    echo $file_name."?".filemtime($_SERVER['DOCUMENT_ROOT'] .$file_name);
}

在HTML中:

<script type="text/javascript" src="<?php latest_version('/a-o/javascript/almanacka.js'); ?>">< /script>

工作原理:

在HTML中,像往常一样写文件路径和名称,但只在函数中。 PHP获取文件的文件时间,并返回文件路径+名称+”?+最新更改时间

你可以用.htaccess来实现

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

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

虽然它是特定于框架的,但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附加一个带有时间戳的查询参数,以确保浏览器在每次请求脚本时都会下载脚本。