Javascript and css caching in asp.net

I know this question has been asked quite a few times and the most common answers were:

  • Automatic versioning using the .htaaccess file.
  • Although not recommended at all, using the 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 it does the job.

I handle some post-release issues, and since we do not follow the lifecycle of a software project per se, we update the site when and when issues are checked and fixed. Therefore, we may have to update the site several times a day compared to no updates for a week.

I'm not sure if there is a way I can still take advantage of caching and at the same time don't need users to refresh the page / clear the cache to see the latest changes.

Is there a way to implement a .htaaccess solution in asp.net if that's what I need to do?

I really appreciate any help.

+3


source to share


1 answer


Here is the solution I used for css files, but should work fine for JS: There is a rule in htaccess:

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

      

This takes a filename, for example "Style_ver_12345.css", and overwrites it in Style.css.



Then, when you include the file, add the LastWriteTime of the actual file ( File.GetLastWriteTime(filePath).Ticks.ToString()

as I do) as the version number. The example file name I would have is Style_ver_634909902200823172.css

This ensures that any change to the file will immediately trigger a new version number, while physical files do not need to have a different name and the file will be cached by the browser.

The user will still have to refresh the page, but they won't need to clear their cache. If you need it, perhaps you can force the update by receiving an ajax call that will compare the version number of the script loaded with the version number on the server. Then a newer version on the server can be forced to update.

+1


source







All Articles