In this tutorial you will learn how bundling and minification works in asp.net mvc application, Bundling technique in asp.net MVC using StyleBundle, ScriptBundle.
When we create any asp.net mvc application, by default one "BundleConfig.Cs" file is added in solution, for bundling in asp.net mvc application there are different type of class like StyleBundle, ScriptBundle for adding files in BundleCollection.
Bundling is very useful features in Asp.net MVC, here you learn how to create a bundle of multiple JavaScript files or CSS files in one http request.
This is also known as minification of javascript file or css files
Open your Asp.net MVC application, go to App_Start folder, there you see BundleConfig.cs, is created by MVC framework by default
There you see two type of bundle class, StyleBundle
and ScriptBundle
, Now you can create as many instance as you need of any of those classes and the finally add to BundleCollection. remember BundleCollection
class will reamin always one only.
There you see many javascript and css files are already added by default, but you can keep on adding your files to RegisterBundle method this way!
public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { //this is an example of adding css file bundles.Add(new StyleBundle("~/Content/css") .Include("~/Content/your_style.css")); //this is an example of adding javascript file bundles.Add(new ScriptBundle("~/bundles/jquery") .Include("~/scripts/your-javascript.js")); } }
You can create a new bundle and add files into that or you can include file in existing bundle , notice in above two example we have included file into existing bundle
Sometimes you may need to add third party script where the version of script may change in future, in such case you don't have to specify a version number of a script file, take a look at the example below where we are adding Jquery files .
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{ bundles.Add(new ScriptBundle("~/bundles/jquery")
.Include("~/Scripts/jquery-{version}.js"));
}
}
So, in future if Jquery version number change in your project, this will automatically pickup and bundle the file.
This how your bundling get executed when application start
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
We also can specify any particular file we want to add in any specific bundle, like bundles.Add(new StyleBundle("~/Content/themes/base/css").Include("~/Content/themes/base/jquery.ui.core.css"))
.
Note: when you add any file in bundle, that will affect the whole application, in case you want that file to be used in any particular page, then don’t add in bundle, instead add the file in that specific page.
Adding too many files in bundle, can slowdown the application performance.