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

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


当前回答

你可以用.htaccess来实现

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

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

其他回答

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

在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有一个很好的例子和解释缓存破坏这里(页面底部)

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

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

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

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

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

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

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