简体   繁体   中英

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.
  2. Although this is not at all recommended, using a version number as a query parameter For example: '/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?

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:

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

That takes a file name such as "Style_ver_12345.css" and rewrites it to 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. An example file name that I would have is 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. A newer version on the server could then force a refresh.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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