How to Add 3rd Party or Custom JavaScript Files or Libraries in ASP.NET MVC 4+

2014-01-18


If you wrote your own JavaScript or jQuery file, and it is not too big, for sure you can place it to any custom folder which you like, and drag it to your view or html file to use it.

But, how about you got big JavaScript or jQuery or other JavaScript library ? or , you have lots of external JavaScript files, you add them to your project and reference to them on each your view files ?

In MVC 4 or later, we should consider use bundle way.

For example, if we want to add Flotr2 library to our project, we put them under a folder Scripts\Other:

image

Then we go to App_Start folder and try to open BundleConfig.cs file:

image

We add the following code in BundleConfig.cs file:

bundles.Add(new ScriptBundle("~/bundles/custom").Include( 
    "~/Scripts/Other/flotr2.js", 
      "~/Scripts/Other/selection.js"));
image

OR:

bundles.Add(new ScriptBundle("~/bundles/custom") 
    .IncludeDirectory(""~/Scripts/Other/", "*.js"));

Note: Actually we do not need to add .min.js file into the bundle because Visual Studio will automatically use or not use min.js file due to your web.config setting.

if we want to use Minification, we should set compiliation debug to false in web.config file:

image

Or, you just add the following code in BundleConfig file if you do not want to change web.config settings.

BundleTable.EnableOptimizations = true;
image

 

How to use the bundle?

If the added JavaScript library will be used for most of your views in your project, just add the following code in _Layout.cshtml file:

@Scripts.Render("~/bundles/custom")

Or, if you only want few of specified views to use it, add the following code in each view:

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

Done.