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

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


当前回答

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

其他回答

在ASP缓存破坏。NET Core通过标记助手将为您处理这个问题,并允许您的浏览器保留缓存的脚本/css,直到文件更改。只需在你的script (js)或link (css)标签中添加标签助手asp-追加-version="true":

<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true"/>

Dave Paquette有一个很好的例子和解释缓存破坏这里(页面底部)

以下是对我有用的:

<head>
<meta charset="UTF-8">
<meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
</head>

如果您正在使用PHP和Javascript,那么以下内容应该适用于您,特别是在您对文件进行多次更改的情况下。所以,每次你都不能改变它的版本。因此,这个想法是在PHP中创建一个随机数,然后将其分配为JS文件的一个版本。

$fileVersion = rand();
<script src="addNewStudent.js?v=<?php echo $fileVersion; ?>"></script>

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

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

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

现在常见的做法是生成一个内容哈希代码作为文件名的一部分,以迫使浏览器(尤其是IE)重新加载javascript文件或css文件。

例如,

vendor.a7561fb0e9a071baadb9.js main.b746e3eb72875af2caa9.js

这通常是构建工具(如webpack)的工作。这里有更多的细节,如果有人想尝试如果你正在使用webpack。