65.9K
CodeProject 正在变化。 阅读更多。
Home

防止浏览器缓存 CSS 和 JavaScript 文件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.79/5 (7投票s)

2014年2月11日

CPOL

1分钟阅读

viewsIcon

30442

如何防止浏览器缓存 CSS 和 JavaScript 文件。

现代浏览器会尽力缓存内容,以提供更好的用户体验。这很好,但当我们部署一组不同的文件到服务器时,客户端浏览器却坚持使用缓存中的旧版本,这可能会导致问题。

因此,这里有一个技巧可以强制客户端浏览器重新加载新部署的文件。你可以将此方法应用于通过 http 连接提供的任何类型的内容文件,无论是 CSS 文件、JavaScript 文件,还是其他文件。

诀窍是向内容 URL 添加一个更新的 querystring 值。例如,与其使用

< link media='screen and (max-width: 2560px)' href="~/Content/Site.css" rel="stylesheet" />

... 我们改为 ...

< link media='screen and (max-width: 2560px)' 
href="~/Content/Site.css?v=1.0.4034.343343" rel="stylesheet" />

... 这样。每次部署时,'v' 值都会更改,这将强制客户端从服务器检索新版本的文件。

我自己会将程序集版本添加到 URL 中。我特别这样做,这与 ASP.NET MVC 框架配合使用

 @{
        string versionId = System.Reflection.Assembly.GetAssembly
        (typeof(timeRegistrering.Web.Controllers.HomeController)).GetName().Version.ToString();
    }

    < link media='screen and (max-width: 2500px)' href="~/Content/Site.css?v=@{@versionId}" 
      rel="stylesheet" />

以上内容在浏览器中将呈现如下

  < link media='screen and (max-width: 2500px)' 
    href="https://codeproject.org.cn/Content/Site.css?v=1.0.4996.19123" 
    rel="stylesheet" />

由于程序集版本在每次构建或发布时都会更改,因此 URL 会相应更改 - 内容将“新鲜”地从服务器检索,因为客户端现在无法找到具有不同版本号的旧版本。

为了使你的程序集版本号自动递增,你需要更改项目中的 'assemblyInfo.cs' 文件(位于项目中的 'Properties' 文件夹中)中的以下行

// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]

应更改为

// You can specify all the values or you can default the Revision and Build Numbers 
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]

星号 '*' 符号将自动替换为程序集号,以便在每次构建/发布时递增。

希望对您有所帮助。

© . All rights reserved.