I am coding a MVC 5 internet application and have a question in regards to JavaScript caching (and caching in general).
Currently, when I update a JavaScript file that is referenced in a view, when I browse to the view, the old JavaScript code is used. If I then refresh the browser, the updated JavaScript code is then used.
This is not ideal, as a user may often browse to a view that has an old JavaScript file, and as such, the view may not be displayed correctly.
I am currently referencing JavaScript files as follows:
@section Scripts{
<script src="~/Scripts/filename.js"></script>
}
Is there a web.config setting that controls caching? Is there a NuGet package that can help with caching?
How can I resolve this situation?
MVC Bundling provides a solution to this problem.
To take advantage of it, add this to your App_Start\BundleConfig.cs
file:
bundles.Add(
new ScriptBundle("~/bundles/filename")
.Include("~/Scripts/filename.js"));
Then in your view:
@section Scripts{
@Scripts.Render("~/bundles/filename")
}
In a Release
build, all the Javascript files in a bundle will be served from a unique URL which contains a hash of their content. This means that if the Javascript files change between builds then the URL of the bundle will change, and so browsers will download the new version.
The bundle is also served with an Expires HTTP header 1 year in the future - improving the response speed of the site on future user visits/page requests. It can safely do this because the URL changes when the bundle content changes.
Even if you're only including a single Javascript file in a page, I'd still create a bundle for it - to take advantage of the cache control, and also the minification.
See the section on "Bundle Caching" in the linked article for a more detailed explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With