MVC 5 JavaScript Caching

I am coding an MVC 5 Internet application and asking a question about JavaScript caching (and caching in general).

Currently, when I update the JavaScript file referenced in the view, when I view the view, the old JavaScript code is used. If I then update my browser, then the updated JavaScript code will be used.

This is not ideal because the user can often view a view that has an old JavaScript file, and as such, the view may not display correctly.

I am currently referencing JavaScript files as follows:

@section Scripts{ <script src="~/Scripts/filename.js"></script> } 

Is there a web.config parameter that controls caching? Is there a NuGet package that can help with caching?

How can I solve this situation?

+5
source share
1 answer

MVC Bundling provides a solution to this problem.

To take advantage of this, add this to your App_Start\BundleConfig.cs file:

 bundles.Add( new ScriptBundle("~/bundles/filename") .Include("~/Scripts/filename.js")); 

Then, in your opinion:

 @section Scripts{ @Scripts.Render("~/bundles/filename") } 

Why does it help

In the Release assembly, all of the bundled Javascript files will be served from a unique URL that contains a hash of their contents. This means that if the Javascript files change between the lines, the package URL will change, and so browsers will download the new version.

In the future, the package will also be used with the Expires HTTP header after 1 year - improving the site’s response speed on subsequent user visits / page requests. This can be done safely because the URL changes when the contents of the package change.

Even if you include only one Javascript file per page, I would still create a package for it - to take advantage of cache control, as well as a mini-code.

For a more detailed explanation, see the "Package Caching" section in a related article.

+3
source

Source: https://habr.com/ru/post/1214723/


All Articles