Pretty straight-forward, I\'m developing an MVC5 application and have noticed (lately) that my Browser appears to be caching the JavaScript code I have on the view within
If you are using Bundling from MVC, you have two options to disable caching:
System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("url", true)
to resolve your script's URL, the second parameter (true
) is requiring a hash to be generated with the URL, thus, preventing caching from your browser when you change the file. This is exactly the same hash generated in the first option, but without minifying.I created a small demo showing that the second option prevents caching from happening, the trick is getting the hash generated from your script's content without minifying your script.
I created a script file called myscript.js
with this content:
$(document).ready(function () {
alert('a');
});
Then I added this to my BundleConfig.cs
:
// PLEASE NOTE this is **NOT** a ScriptBundle
bundles.Add(new Bundle("~/bundles/myscripts").Include(
"~/Scripts/myscript*"));
If you add a ScriptBundle
, you will get a minified response again, since ScriptBundle
is just a Bundle
using JsMinify
transformation (source). That's why we just use Bundle
.
Now you can just add your script using this method to resolve the script URL with the hash appendend. You can use the Script.Render
@Scripts.Render(System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/myscripts", true))
Or the script
tag:
Either way will generate a URL with a hash to prevent caching:
After editing my file: