如何让 index.html 在 AngularJS 网站内容发生变化时不缓存?

How to make index.html not to cache when the site contents are changes in AngularJS website?

通常对于 .js.css 文件,我们将在构建过程中附加一个版本,例如 xx.js?v=123,然后网站部署后,我们可以得到新版本的js和CSS。但是我没有看到一个地方在谈论如何在网站部署时进行 index.html 文件升级。我们确实在 IE 中看到 HTML 内容应该已经更改,但它仍然使用旧的 HTML 内容。

我从 google 中找到的一个解决方案是

<meta http-equiv="Cache-control" content="no-cache">

但是,我不确定这是否是最好的解决方案?

是的,这是正确的方法。您必须设置 Cache-Control header 让浏览器知道他们不必为该请求缓存任何内容。

<meta http-equiv="Cache-control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">

(Pragma & Cache-Control 是一回事,但来自不同的 HTTP 规范。请在此处查看答案:Difference between Pragma and Cache-control headers?)

在此处查看相关答案之一:How to burst yeoman index.html cache

如评论中所述,它确实是您想要查看的服务器配置,但您没有提到您的设置。我们 运行 我们的 AngularJS 站点具有使用 IIS 的 .NET 后端。

我们定期更新我们的网站,过去曾遇到过 JS 和 CSS 资源缓存问题,但我们已通过以下设置解决了该问题:

建造

我们使用 gulp 构建我们的 AngularJS 应用程序,作为其中的一部分,我们将版本号附加到我们的主应用程序 CSS 和 Javascript 文件的查询字符串中经常变化。例如:

<link href="css/default.min.css?v=2" rel="stylesheet" />

服务器配置

在根 web.config 中,我们通过设置 cache-controlPragmaExpires 来指定我们不希望 index.html 缓存请求 headers 以及 max-age 到 0.

<location path="index.html">
<system.webServer>
  <staticContent>
    <clientCache cacheControlMode="DisableCache" cacheControlMaxAge="0.00:00:00" />
  </staticContent>
    <httpProtocol>
        <customHeaders>
            <add name="Cache-Control" value="no-cache, no-store, must-revalidate" />
            <add name="Pragma" value="no-cache" />
            <add name="Expires" value="-1" />
        </customHeaders>
    </httpProtocol>  
</system.webServer>
</location>

参考文献:

通过将 content 值设置为 0,浏览器将始终从 Web 服务器加载页面。

<meta http-equiv="expires" content="0">

您可以从未启用预加载的特定站点高级设置中指定 IIS。但是,您的网站性能会受到影响。还要检查特定网站的应用程序池是否在 .NET CLR 版本上集成了管道模式。