5.8. Bundles
Bundles are used to make it easier to link JavaScript scripts and CSS files. You can link CSS bundles with the Styles.Render
helper and script bundles with the Scripts.Render
helper.
Bundles are registered in the BundleConfig.cs
file located in the App_Start
folder:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/jquery-ui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/jquery-ui.min.css",
"~/Content/themes/ui-darkness/jquery-ui.min.css",
"~/Content/themes/ui-darkness/theme.css",
"~/Content/bootstrap.min.css",
"~/Content/Site.css"
));
}
The RegisterBundles
method adds all created bundles to the bundles collection. A bundle is declared in the following way:
new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js")
The virtual path of the bundle is passed to the ScriptBundle
construct. Specific script files are included in this bundle using the Include
method.
The {version}
parameter in the “~/Scripts/jquery-{version}.js
” expression is a placeholder for any string referring to the script version. It is very handy because it allows the version of the library to be changed later without having to change anything in the code. The system will accept the new version automatically.
The “~/Scripts/jquery.validate*
” expression fills out the rest of the string with the asterisk character as a wildcard. For example, the expression will include two files at once in the bundle: jquery.validate.js
and jquery.validate.unobtrusive.js
, along with their minimized versions, because their names both start with “jquery.validate
”.
The same applies when creating CSS bundles, using the StyleBundle
class.
The full versions of the scripts and cascading style sheets should be used in the debug mode and the minimized ones in the release mode. Bundles allow you to solve this problem. When you run the application in the debug mode, the |