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

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


当前回答

location.reload(真正的);

参见https://www.w3schools.com/jsref/met_loc_reload.asp

我动态调用这行代码,以确保javascript已经从web服务器重新检索,而不是从浏览器的缓存,以避免这个问题。

其他回答

将当前时间附加到URL确实是一种常见的解决方案。但是,如果你愿意,你也可以在web服务器级别管理它。服务器可以配置为javascript文件发送不同的HTTP头。

例如,要强制文件缓存不超过1天,你可以发送:

Cache-Control: max-age=86400, must-revalidate

对于测试版,如果你想强迫用户总是获得最新的,你可以使用:

Cache-Control: no-cache, must-revalidate

我们一直在为用户创建一个SaaS,并为他们提供一个脚本,以附加在他们的网站页面,它是不可能附加一个版本的脚本,因为用户将附加脚本到他们的网站的功能,我不能强迫他们改变版本,每次我们更新脚本

因此,我们找到了一种方法,在用户每次调用原始脚本时加载脚本的新版本

提供给用户的脚本链接

<script src="https://thesaasdomain.com/somejsfile.js" data-ut="user_token"></script>

脚本文件

if($('script[src^="https://thesaasdomain.com/somejsfile.js?"]').length !== 0) {
   init();
} else {
   loadScript("https://thesaasdomain.com/somejsfile.js?" + guid());
}

var loadscript = function(scriptURL) {
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = scriptURL;
   head.appendChild(script);
}

var guid = function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

var init = function() {
    // our main code
}

解释:

用户已经在他们的网站上附加了脚本,我们使用jQuery选择器检查脚本附加的唯一标记是否存在,如果不存在,则使用更新的标记(或版本)动态加载它

这是调用相同的脚本两次,这可能是一个性能问题,但它确实解决了强制脚本不从缓存加载的问题,而不将版本放在给定给用户或客户端的实际脚本链接中

免责声明:如果在您的情况下性能是一个大问题,请不要使用。

在asp.net mvc中,你可以使用@DateTime.UtcNow.ToString()来表示js文件的版本号。版本号自动改变日期和你强迫客户端浏览器自动刷新js文件。我使用这种方法,这是工作良好。

<script src="~/JsFilePath/JsFile.js?v=@DateTime.UtcNow.ToString()"></script>
<script>  
  var version = new Date().getTime();  
  var script = document.createElement("script");  
  script.src = "app.js?=" + version;  
  document.body.appendChild(script);  
</script>

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

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

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