I was looking for a nice way how to force browsers to refresh its cached version of files and reload script files after the change occured.
Usually we link JS files or CSS files like this:
1 |
<script type='text/javascript' src="/_layouts/js/myJavascriptFile.js"></script> |
If you want to force refresh, you can amend parameters to url, ie.
1 |
<script type='text/javascript' src="/_layouts/js/myJavascriptFile.js?version=1"></script> |
Well, this is manual way, so how do it in automated way, so I do not have to care about it? There is several ways how to do it, I will just mention one, which is simple and reliable and you do not have to remember to increase anything upon deployment. (it’s not my idea, thanks to Adam Tegen and his answer in stackoverflow). I took the liberty to change it so it’s possible to use in ASP.NET webforms as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public static class VersionLinkHelper { public static string GetVersion(string fileName) { var context = HttpContext.Current; if (context.Cache[fileName] == null) { var physicalPath = context.Server.MapPath(fileName); var version = "?v=" + new System.IO.FileInfo(physicalPath).LastWriteTime .ToString("yyyyMMddhhmmss"); context.Cache.Add(physicalPath, version, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero, CacheItemPriority.Normal, null); context.Cache[fileName] = version; return fileName+version; } else { return fileName + context.Cache[fileName] as string; } } } |
In ASP.NET page link the file as:
1 |
<script type='text/javascript' src='<%= VersionLinkHelper.GetVersion("/_layouts/js/CS/myJavascriptFile.js") %>'></script> |