我注意到一些浏览器(特别是Firefox和Opera)非常热衷于使用.css和.js文件的缓存副本,甚至在浏览器会话之间。当您更新其中一个文件时,这会导致一个问题,但用户的浏览器会继续使用缓存的副本。

当文件发生更改时,强迫用户浏览器重新加载文件的最优雅的方法是什么?

理想情况下,该解决方案不会强制浏览器在每次访问页面时重新加载文件。


我发现John Millikin和da5id的建议很有用。这有一个专门的术语:自动版本控制。

我在下面发布了一个新的答案,这是我最初的解决方案和约翰的建议的结合。

SCdF建议的另一个想法是将伪查询字符串附加到文件中。(一些自动使用时间戳作为伪查询字符串的Python代码是由pi..提交的)

然而,关于浏览器是否缓存带有查询字符串的文件还存在一些讨论。(请记住,我们希望浏览器缓存该文件并在以后的访问中使用它。我们只希望它在文件更改时再次获取该文件。)


当前回答

"Another idea which was suggested by SCdF would be to append a bogus query string to the file. (Some Python code to automatically use the timestamp as a bogus query string was submitted by pi.) However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.) Since it is not clear what happens with a bogus query string, I am not accepting that answer."

<link rel="stylesheet" href="file.css?<?=hash_hmac('sha1', session_id(), md5_file("file.css")); ?>" />

哈希文件意味着当文件发生变化时,查询字符串也会发生变化。如果没有,它将保持不变。每个会话也强制重新加载。

此外,您还可以使用重写使浏览器认为它是一个新的URI。

其他回答

"Another idea which was suggested by SCdF would be to append a bogus query string to the file. (Some Python code to automatically use the timestamp as a bogus query string was submitted by pi.) However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.) Since it is not clear what happens with a bogus query string, I am not accepting that answer."

<link rel="stylesheet" href="file.css?<?=hash_hmac('sha1', session_id(), md5_file("file.css")); ?>" />

哈希文件意味着当文件发生变化时,查询字符串也会发生变化。如果没有,它将保持不变。每个会话也强制重新加载。

此外,您还可以使用重写使浏览器认为它是一个新的URI。

如果你正在使用Git和PHP,你可以在每次Git存储库中有变化时从缓存中重新加载脚本,使用以下代码:

exec('git rev-parse --verify HEAD 2> /dev/null', $gitLog);
echo '  <script src="/path/to/script.js"?v='.$gitLog[0].'></script>'.PHP_EOL;

只需在你想要硬重载(强制浏览器重载缓存的CSS和JavaScript文件)的地方添加以下代码:

$(window).load(function() {
    location.reload(true);
});

在.load中执行此操作,这样它就不会像循环一样刷新。

我将文件内容的MD5哈希值放在其URL中。这样我就可以设置一个很长的过期日期,而不必担心用户使用旧的JS或CSS。

我还在运行时(或在文件系统更改时)对每个文件进行一次计算,因此在设计时或构建过程中没有什么有趣的事情要做。

如果你使用ASP。NET MVC,那么你可以在我的另一个答案中查看代码。

在ASP。NET Core你可以通过添加'asp-追加-版本'来实现:

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

 <script src="~/js/xxx.js" asp-append-version="true"></script>

它将生成HTML:

<link rel="stylesheet" href="/css/xxx.css?v=rwgRWCjxemznsx7wgNx5PbMO1EictA4Dd0SjiW0S90g" />

每当您更新文件时,框架将生成一个新的版本号。