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

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


当前回答

如何添加文件大小作为加载参数?

<script type='text/javascript' src='path/to/file/mylibrary.js?filever=<?=filesize('path/to/file/mylibrary.js')?>'></script>

因此,每次更新文件时,“filever”参数都会改变。

当您更新文件并且您的更新结果是相同的文件大小时,情况会如何?几率有多大?

其他回答

ASP。NET我认为下一个具有高级选项的解决方案(调试/发布模式,版本):

Js或Css文件包括如下方式:

<script type="text/javascript" src="Scripts/exampleScript<%=Global.JsPostfix%>" />
<link rel="stylesheet" type="text/css" href="Css/exampleCss<%=Global.CssPostfix%>" />

全球。JsPostfix和Global。在Global.asax中,CssPostfix的计算方法如下:

protected void Application_Start(object sender, EventArgs e)
{
    ...
    string jsVersion = ConfigurationManager.AppSettings["JsVersion"];
    bool updateEveryAppStart = Convert.ToBoolean(ConfigurationManager.AppSettings["UpdateJsEveryAppStart"]);
    int buildNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Revision;
    JsPostfix = "";
#if !DEBUG
    JsPostfix += ".min";
#endif      
    JsPostfix += ".js?" + jsVersion + "_" + buildNumber;
    if (updateEveryAppStart)
    {
        Random rand = new Random();
        JsPosfix += "_" + rand.Next();
    }
    ...
}

最简单的解决方案?不要让浏览器缓存。将当前时间(以毫秒为单位)作为查询追加。

(您仍然处于测试阶段,因此您可以合理地选择不优化性能。但这里有YMMV。)

据我所知,一个常见的解决方案是在脚本的src链接中添加?<version>。

例如:

<script type="text/javascript" src="myfile.js?1500"></script>

我假设在这一点上,没有更好的方法比查找-替换增量这些“版本号”在所有的脚本标签?

你可以让版本控制系统帮你做这件事?例如,大多数版本控制系统都有一种方法可以在签入时自动注入修订号。

它看起来是这样的:

<script type="text/javascript" src="myfile.js?$$REVISION$$"></script>

当然,总有更好的解决方案。

jQuery函数getScript也可以用来确保每次页面加载时确实加载了js文件。

我是这样做的:

$(document).ready(function(){
    $.getScript("../data/playlist.js", function(data, textStatus, jqxhr){
         startProgram();
    });
});

请登录http://api.jquery.com/jQuery.getScript/查看该功能

默认情况下,$. getscript()将缓存设置设置为false。这将向请求URL附加一个带有时间戳的查询参数,以确保浏览器在每次请求脚本时都会下载脚本。

location.reload(真正的);

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

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