Prevent ASP.NET MVC Bundles Loading more than once

Tim picture Tim · Sep 20, 2012 · Viewed 7.6k times · Source

is there an inbuilt method of tracking if a bundle has already been loaded? I have several edit views which forexample require jquery and jquery.Validate etc libraries. Which i don't need to reference on the main layout page. Since a page could consist of several different conditional libraries ... ideally i would like @scripts.Render to know if i have already referenced a library and prevent its reloading.

Cheers Tim

Answer

gidmanma picture gidmanma · Oct 8, 2012

I think both Hao Kung and user108 have pieces of your answer.

Hao Kung is addressing the system's ability to know that you have already included a bundle on the page and to avoid adding a duplicate. This is similar to what WordPress's enqueue script/style does. MVC does not have this yet. You would have to build it yourself.

user108 is presenting a possible solution to your problem. He/she is saying that in your layout you can create an optional "Scripts" section. Then, in the views that require the jquery validation code you can include it in the "Scripts" section of the layout. This would accomplish most of what you are looking for. The only place it would not work is if you have multiple view partials on the same page that all require the jquery validation code.

You could implement a solution for this yourself fairly easily. Here's a SO post that will get you started.