Removing cache with MVC5 bundling
Today, I want to share how to force browser to reload cached js files.
We often experience that our updated js files don’t reflect the changes when deployed.
This is because of the browser cache. The general(and widely used) solution is to append some random number to js file name(Yes I was using this method on our current applications).
This could be a solution but not a good one because it loads js files on every load.
We can use cached Js fils if there are no changes with them and refresh only when they are changed.
Below approach uses MVC5 bundling and application versioning.
http://www.jomendez.com/2016/05/26/how-to-avoid-js-files-cache-script-bundle-with-razor/
Bundling helps you packaging your js files into bundle. This bundling reduces application initial load time.
Please note below screenshots one without bundling and one with bundling.
Bundling took about 547ms on initial load where normal js call took 1400ms.
Referring above article, I added below script to _Layout.cshtml.
@{
string version = typeof(WebApiApplication).Assembly.GetName().Version.ToString();}@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}?nocache=" + version + "\"></script>", "~/bundles/modernizr")@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}?nocache=" + version + "\"></script>", "~/bundles/jquery")@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}?nocache=" + version + "\"></script>", "~/bundles/jqueryui")@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}?nocache=" + version + "\"></script>", "~/bundles/jquery-confirm")@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}?nocache=" + version + "\"></script>", "~/bundles/jqueryval")@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}?nocache=" + version + "\"></script>", "~/bundles/bootstrap)
Note that our application version need to be updated in order to use this feature.
With this setup, our application will load new js files only when we intended.
Thanks for reading.