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

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


当前回答

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

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

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

其他回答

在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获取文件的文件时间,并返回文件路径+名称+”?+最新更改时间

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

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

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

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

你可以添加文件版本到你的文件名,这样它就像:

https://www.example.com/script_fv25.js

fv25 =>文件版本号25

在你的.htaccess中放入这个块,它将从链接中删除版本部分:

RewriteEngine On
RewriteRule (.*)_fv\d+\.(js|css|txt|jpe?g|png|svg|ico|gif) $1.$2 [L]

所以最后一个链接是:

https://www.example.com/script.js

ASP。NET页面我正在使用以下

之前

<script src="/Scripts/pages/common.js" type="text/javascript"></script>

AFTER(强制重载)

<script src="/Scripts/pages/common.js?ver<%=DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>

添加DateTime.Now.Ticks效果很好。