Thursday, January 11, 2018

How to force browser to update javascript files cache after deployment?

If you’re developing your project you might notice that in some browsers the changes you’ve made to your javascript files do not take effect immediately.

Sometimes it’s necessary to do a hard refresh[ctrl+f5] to see the updates take effect. But it’s unlikely that average web users know what a hard refresh is [because every one is not a developer :), nor can you expect them to keep refreshing the page until things straighten out even its not a good idea to ask user to refresh the page to see the current modification .. lol .

So how can you ensure that any updates you’ve made to your javascript will take place immediately for all users?

Here is the answer :)
I Created a javascript extension class, which has a static method and that method will embed a version to the end of the supplied javascript file.
public static class JavascriptExtension
{

   public static MvcHtmlString IncludeVersionInJs(this HtmlHelper helper, string filename)
   {
      string version = GetLastVersionNumber(helper, filename);
      return MvcHtmlString.Create("");
   }

  private static string GetLastVersionNumber(this HtmlHelper helper, string filename)
 {
   var context = helper.ViewContext.RequestContext.HttpContext;
   if (context.Cache[filename] == null)
   {
    var physicalPath = context.Server.MapPath(filename);
    var versionNo = $"?versionNo={new      System.IO.FileInfo(physicalPath).LastWriteTime.ToString("MMddHHmmss")}";

    context.Cache.Add(filename, versionNo, null,
    DateTime.Now.AddMinutes(5), TimeSpan.Zero,
    CacheItemPriority.Normal, null);
    return versionNo;
   }
   else
   {
      return context.Cache[filename] as string;
    }
  }
}

How to use this now? 

Use bellow code in your .cshtml pages
@Html.IncludeVersionInJs("/yourjavascriptfilename.js")

it will look like on the source as bellow

"type='text/javascript' src='/yourjavascriptfilename.js?versionNo=1218154859"
in the script tag

means when ever you changes on your javascript file and deploy to the server it will always compare with the versionNo from the cache and if found that related file has any changes then browser will download the latest one. So now you do not need to hard refresh the page and not to ask user to do the same.. :) 


Enjoy Coding :) and continue reading for next topic.