简体   繁体   English

在asp.net中的Javascript和css缓存

[英]Javascript and css caching in asp.net

I know this question was asked quite a few times and the most common answers were: 我知道这个问题被问过很多次,最常见的答案是:

  1. Auto versioning using the .htaaccess file. 使用.htaac​​cess文件自动进行版本控制。
  2. Although this is not at all recommended, using a version number as a query parameter For example: '/scripts/script1?v=1.0.0'. 虽然根本不建议这样做,但使用版本号作为查询参数例如:'/ scripts / script1?v = 1.0.0'。 This will cause the browser not to cache the file but does the job. 这将导致浏览器不缓存文件但完成工作。

I am handling some post release issues and since we don't follow a software project life cycle as such, we update the site as and when the issues are tested and fixed. 我正在处理一些发布后问题,因为我们不遵循软件项目生命周期,所以我们会在测试和修复问题时更新网站。 So, we may have to update the site several times a day sometimes versus no updates for a week. 因此,我们可能需要每天多次更新网站,而不是一周更新。

I am not sure if there is a way I can still take the benefit of caching and at the same time don't need to have the users to refresh the page/clear cache to see latest changes. 我不确定是否有一种方法我仍然可以利用缓存,同时不需要让用户刷新页面/清除缓存以查看最新的更改。

Is there a way I can implement the .htaaccess solution in asp.net if that's what I need to do? 有没有办法在asp.net中实现.htaac​​cess解决方案,如果这是我需要做的事情?

I really appreciate any help. 我非常感谢任何帮助。

Here is the solution I've used for css files, but should work fine for JS: In the htaccess have a rule: 这是我用于css文件的解决方案,但应该适用于JS:在htaccess中有一个规则:

RewriteRule ^(.*)_ver_.*(\..*)$ $1$2 [NC,L]

That takes a file name such as "Style_ver_12345.css" and rewrites it to Style.css. 这需要一个文件名,如“Style_ver_12345.css”,并将其重写为Style.css。

Then when when you include the file append the LastWriteTime of the actual file ( File.GetLastWriteTime(filePath).Ticks.ToString() is how I do it) as the version number. 然后当你包含文件时,将实际文件的File.GetLastWriteTime(filePath).Ticks.ToString()就是我的工作方式File.GetLastWriteTime(filePath).Ticks.ToString()为版本号。 An example file name that I would have is Style_ver_634909902200823172.css 我将拥有的示例文件名是Style_ver_634909902200823172.css

This will ensure that any change in the file will immediately cause a new version number, while the physical files does not need to have a different name, and the file will be cached by the browser. 这将确保文件中的任何更改将立即导致新的版本号,而物理文件不需要具有不同的名称,并且文件将由浏览器缓存。

The user would still have to refresh the page, but they wouldn't have to clear their cache. 用户仍然需要刷新页面,但他们不必清除缓存。 If you needed to, maybe you could force a refresh by having an ajax call that would compare the version number of the script loaded with the version number on the server. 如果你需要,也许你可以通过ajax调用强制刷新,该调用将比较加载的脚本的版本号和服务器上的版本号。 A newer version on the server could then force a refresh. 然后,服务器上的较新版本可以强制刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM