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

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

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


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

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

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

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


当前回答

在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" />

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

其他回答

另一个关于ASP的建议。网的网站,

Set different cache-control:max-age values, for different static files. For CSS and JavaScript files, the chances of modifying these files on server is high, so set a minimal cache-control:max-age value of 1 or 2 minutes or something that meets your need. For images, set a far date as the cache-control:max-age value, say 360 days. By doing so, when we make the first request, all static contents are downloaded to client machine with a 200-OK response. On subsequent requests and after two minutes, we see 304-Not Modified requests on CSS and JavaScript files which avoids us from CSS and JavaScript versioning. Image files will not be requested as they will be used from cached memory till the cache expires. By using the below web.config configurations, we can achieve the above described behavior, <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <staticContent> <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00.00:01:00"/> </staticContent> <httpProtocol> <customHeaders> <add name="ETAG" value=""/> </customHeaders> </httpProtocol> </system.webServer> <location path="Images"> <system.webServer> <staticContent> <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="180.00:00:00" /> </staticContent> </system.webServer> </location>

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

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

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

我不知道为什么你们要花这么大的力气来实现这个解决方案。

您所需要做的就是获取文件修改后的时间戳,并将其作为查询字符串附加到文件中。

在PHP中,我会这样做:

<link href="mycss.css?v=<?= filemtime('mycss.css') ?>" rel="stylesheet">

filemtime()是一个PHP函数,返回修改后的文件时间戳。

我没有发现客户端DOM方法动态创建脚本节点(或CSS)元素:

<script>
    var node = document.createElement("script");
    node.type = "text/javascript";
    node.src = 'test.js?' + Math.floor(Math.random()*999999999);
    document.getElementsByTagName("head")[0].appendChild(node);
</script>

我建议执行以下流程:

无论何时部署你的CSS和JavaScript文件。类似于:screen.1233.css(如果您使用版本控制系统,该数字可以是您的SVN版本) 缩小它们以优化加载时间