Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 JavaScript Caching [duplicate]

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?

like image 786
user3736648 Avatar asked Mar 05 '15 09:03

user3736648


1 Answers

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")
}

Why this helps

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.

like image 144
Ross McNab Avatar answered Sep 30 '22 05:09

Ross McNab