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>

其他回答

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效果很好。

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

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

使用版本GET变量来防止浏览器缓存。

在url末尾附加?v=AUTO_INCREMENT_VERSION可以防止浏览器缓存-避免任何和所有缓存的脚本。

这种用法已被弃用: https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache

这个答案只晚了6年,但我在很多地方都没有看到这个答案……HTML5引入了应用程序缓存来解决这个问题。我发现我正在编写的新服务器代码正在破坏人们浏览器中存储的旧javascript,所以我想找到一种方法让他们的javascript过期。使用如下所示的清单文件:

CACHE MANIFEST
# Aug 14, 2014
/mycode.js

NETWORK:
*

并在每次您希望用户更新其缓存时,使用新的时间戳生成此文件。作为旁注,如果您添加了这个,浏览器将不会重新加载(即使当用户刷新页面时),直到清单告诉它。

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

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