This article continues from my previous article that described the bundling features basics and showed how it helps us to reduce the page processing time, if you haven't looked at it then kindly go through the following URL.
Bundling in MVC4
Well apart from the features discussed in my previous article there are a few more new features that I would like to be introduced as the advanced features of bundling in MVC4. The following is the list.
1. bundles.UseCDN property:
This property is used to read the contents of the script, images, CSS from online, for which you provide the path. CDN is an abbreviation for “Content Delivery Network”. When you set the value of this property to “true” then you provide the online CDN path for that script, images, CSS as the second parameter for the ScriptBundle / StyleBundle class. The problem with this approach is that it may often fail because of incorrect CDN path/url, or due to some network failure. So when you provide the CDN path then you need to provide the failure mechanism like how to handle an exception inside your catch block. In the same manner you need to check whether the CDN failed or not, if it failed then you need to manually load the scripts, images and CSS files from your application. The following is the syntax of using the CDN property when bundling:
- #region UseCDN
- //1. For Using CDN property
-
- bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/*.css"));
- // Content Delivery Network
- bundles.UseCdn = true;
- BundleTable.EnableOptimizations = true;
- var jqueryPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";
-
- bundles.Add(new ScriptBundle("~/bundles/jquery", jqueryPath).Include(
- "~/Scripts/jquery-{version}.js",
- "~/Scripts/jquery.unobtrusive*",
- "~/Scripts/jquery.validate*"
- ));
-
- #endregion
In the preceding scenario of using the CDN property, the script images and CSS file will be requested from the CDN path/url when in release/deployment mode and in the case of development mode the file would be requested from the local application. As we pointed out earlier we need to have a failure mechanism if in case the CDN fails. So for this we can implement this mechanism inside the _Layout.cshtml file (where we will render this script, images and CSS). The following would be the code:
“_Layout.cshtml”
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width" />
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @*@Scripts.Render("~/bundles/modernizr")*@
- </head>
- <body>
- @RenderBody()
- @Scripts.Render("~/bundles/jquery")
-
- <script type="text/javascript">
- //checking for the jquery is loaded or not. You can also cheche the same by using the below commented line
- //if(typeof($)=='function') && typeof(jQuery)=='function')
- if (typeof jQuery == undefined) {
- //creating the script element
- var e = document.createElement("script");
- //setting the src attribute of the script to load dynamically
- e.src = '@Url.Content("~/Scripts/jquery-1.7.1.min.js")';
- //settting the type of the script
- e.type = 'text/javascript';
- //appending the newly created script element in the header section of the html page
- document.getElementByTagName("head")[0].appendChild(e);
- }
- </script>
- @RenderSection("scripts", required: false)
- </body>
- </html>
Just try running the application, once the page is loaded press the F12 key to open the “F12 developer tools” in Google Chrome then go to the Network Tab and again refresh the page by pressing the F5 key. You'll find that since you haven't set the debug attribute to “false” it will load all the script and CSS files from the local application only. Now let's try to force the MVC application to use the CDN path by setting the “EnableOptimizations” property of the BundleTable class inside the BundleConfig.cs file or by setting the compilation debug attribute value to ”false” in the web.config file. Just write the following line beneath your bundle.UseCdn=”true” line.
- BundleTable.EnableOptimizations = true;
Or set the Compilation debug attribute in the web.config file to “false”.
- <compilation debug="false" targetFramework="4.0"/>
And again run the application. This time you'll find that the file has been downloaded from the CDN path. Here is the snapshot for it.
NOTE:
- From the preceding screenshot you can find that the jQuery file is been downloaded from the CDN path provided by us.
- From the preceding screenshot you can also find the single blob CSS file that is returned by the MVC, if you open that file by just clicking it, you'll find that the MyStyle.css file (classes) is first added and then the Site.css file (classes) are added. That's because we are implementing the virtual parth “~/Content/css with the following code in the BundleConfig.cs file:
- bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/*.css"));
Since the wildcard character “*” is used, so the default ordering of the CSS files would be made alphabetically done by the MVC. As opposed to this if you provide MVC with the order of the files, then it will render those files in the same order that you provided to the MVC as in the case of jQuery script files. For for example inside the BundleConfig.cs file if you provide the StyleBundle Configuration as below:
- bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/Site.css").Include("~/Content/MyStyle.css"));
Then in the preceding scenario MVC will load first the Site.css and then the MyStyle.css file.
2. Using IBundleOrderer
This interface allows us to order the Bundles in our own way, in other words it takes the Bundle order in the way we've added them in the
BundleConfig.cs file. If in your application you are not using any Custom class that implements the IBundleOrderer interface then in that case the
DefaultBundleOrderer class is used to bundle your scripts and .css files. Like in the case of the Controller the
DefaultControllerFacotry class is used to process the user request, if your application doesn't have any
CustomControllerFactory defined inside your application. For more information about the
ControllerFactory you may use the following link.
CustomControllerFactory in MVC4In the case of the DefaultBundleOrderer class the way it works is a little bit different for css/script/image files. For example if in case your application requires some sort of ordering of CSS/Scripts files and for such your created a bundle like the following one.
- //2. For demonstrating the IBundleOrderer interface
-
- Bundle styleBundle = new StyleBundle("~/Content/css")
- .Include("~/Content/Site.css")
- .Include("~/Content/MyStyle.css");
- bundles.Add(styleBundle);
-
- var scriptBundle = new Bundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js")
- .Include("~/Scripts/jquery.unobtrusive*")
- .Include("~/Scripts/jquery.validate*")
- .Include("~/Scripts/Home/Index.js");
Try running the application, you may find that some of the dependent files are loaded earlier then the parent/ required files on whom they are dependent. For example look at the following screenshot. You can find that the jquery.validate.unobtrusive.js file is loaded before the file jquery.validate.js file. That may create problems for the normal functioning of the application.
The reason for the preceding download of script files, is that it may happen because the DefaultBundleOrderer might not consider the order of the Script/css files that you've provided using the Include function and it tries to render the script files, by making use the FileSetOrderList property of the BundleCollection class. This property is of type BundleFileSetOrdering class that comes with the default set of ordering for scripts and CSS files defined within the method “AddDefaultFileOrderings”. The following is the snapshot for it from my solution.
These are 7 sets of the default FileSetOrderList. You can expand the node and check it.
Or else click the following link:
Ordering of Files within a bundle - What are the known libraries?It may often happen that the dependent script files are loaded earlier than the main script files that may cause chaotic results leading to script failure errors or an undesired look and feel of your view/page. To overcome this issue we can have a custom class that can implement the “IBundleOrderer” interface where you can specify the file orders and the MVC application will render those files in that order only. This interface lies inside the “
System.Web.Optimization” namespace. To demonstrate this I'm creating a new folder inside my application with the name “Utility” and within this folder I'm creating a new class with the name “
MyCustomBundleOrderer” that implements the “IBundleOrderer” interface.
NOTE: In case your application is using the CSS files with the name “reset.css” and “normalize.css”, then as per the DefaultBundleOrderer it will add the “reset.css” file first and then the “normalize.css” file”. For this you can have a look at the default ordering of CSS and script file managed by the DefaultBundleOrderer class.
Ordering of Files within a bundle - What are the known libraries?If you want to override the processing by the DefaultBundleOrderer class then you need to implement the IBundleOrderer interface.
The folllowing is the code snippet for it:
- public class MyCustomBundleOrderer : IBundleOrderer
- {
- public IEnumerable<FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files)
- {
-
- string[] highPriorityCssOrScripts = { "Site.css", "MyStyle.css", "jquery-1.7.1.js", "jquery-ui- 1.8.20.js", "jquery.validate.js", "jquery.unobtrusive-ajax.js", "jquery.validate.unobtrusive.js" };
-
- List<FileInfo> lstOrderedFiles = new List<FileInfo>();
-
-
- foreach (string strCssOrScriptName in highPriorityCssOrScripts)
- {
- FileInfo fileObj = files.FirstOrDefault(delegate(FileInfo fObj)
- {
- return fObj.Name.Equals(strCssOrScriptName, StringComparison.InvariantCultureIgnoreCase);
- });
- if (fileObj != null)
- {
- lstOrderedFiles.Add(fileObj);
- }
- }
-
-
- foreach (FileInfo lowFileInfo in files)
- {
- if (!lstOrderedFiles.Contains(lowFileInfo))
- {
- lstOrderedFiles.Add(lowFileInfo);
- }
- }
-
- return lstOrderedFiles;
- }
- }
And update the BundleConfig.cs file to use the MyCustomBundleOrderer interface. The following is the code snippet for that.
- #region IBundleOrderer
- //2. For using the IBundleOrderer interface
-
- var styleBundle = new Bundle("~/Content/css");
- styleBundle.Orderer = new MyCustomBundleOrderer();
- styleBundle.Include("~/Content/Site.css");
- styleBundle.Include("~/Content/MyStyle.css");
- bundles.Add(styleBundle);
-
- var scriptBundle = new Bundle("~/bundles/jquery");
- //setting the IBundleOrderer by our custom BundleOrderer Classs
- scriptBundle.Orderer = new MyCustomBundleOrderer();
- scriptBundle.Include("~/Scripts/jquery-{version}.js")
- .Include("~/Scripts/jquery.unobtrusive*")
- .Include("~/Scripts/jquery.validate*");
- //add the scriptBundle object to the bundles Collection
- bundles.Add(scriptBundle);
-
- #endregion
Also update the
_Layout.cshtml file. Here is the code snippet for that.
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width" />
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @* @Styles.Render("~/Content/MyStyle")*@
-
- @* <link rel="Stylesheet" type="text/css" href="@Styles.Url("~/Content/css")" />*@
-
- </head>
- <body>
- @RenderBody()
-
- @* <script type="text/javascript" src="@Scripts.Url("~/bundles/jquery")"></script>*@
-
- @Scripts.Render("~/bundles/jquery")
-
- @*
- <script type="text/javascript">
- //checking for the jquery is loaded or not. You can also cheche the same by using the below commented line
- //if(typeof($)=='function') && typeof(jQuery)=='function')
- if (typeof jQuery == undefined) {
- //creating the script element
- var e = document.createElement("script");
- //setting the src attribute of the script to load dynamically
- e.src = '@Url.Content("~/Scripts/jquery-1.7.1.min.js")';
- //settting the type of the script
- e.type = 'text/javascript';
- //appending the newly created script element in the header section of the html page
- document.getElementByTagName("head")[0].appendChild(e);
- }
- </script>*@
- @RenderSection("scripts", required: false)
- </body>
- </html>
Now try to run your application and go to the network tab. The following would be the snapshot of yours.
NOTE: If for rendering the css/script file you use the way like the following one described in for example. Then you'll get a single blob of CSS or script file that will load all the CSS and script files in a single file for CSS and script separately. For example:
- <script type="text/javascript" src="@Scripts.Url("~/bundles/jquery")"></script>
The preceding script will print the snapshot.
3. Using BundleFileSetOrdering: You can also use this class for maintaining the order of the Script files. The following is code that you need to implement for using the BundleFileSetOrdering class for sorting the script or CSS files. This could be implemented in the following two ways:
- Implementing directly inside the BundleConfig.cs file
The following is the code snippet:
- #region BundleFileSetOrdering
-
- bundles.FileSetOrderList.Clear();
-
- BundleFileSetOrdering cssOrScriptFileSetOrdering = new BundleFileSetOrdering("script");
- cssOrScriptFileSetOrdering.Files.Add("~/Content/reset.css");
- cssOrScriptFileSetOrdering.Files.Add("~/Content/normalize.css");
- cssOrScriptFileSetOrdering.Files.Add("~/Content/Site.css");
- cssOrScriptFileSetOrdering.Files.Add("~/Content/MyStyle.css");
- cssOrScriptFileSetOrdering.Files.Add("~/Scripts/jquery-{version}.js");
- cssOrScriptFileSetOrdering.Files.Add("~/Scripts/jquery.unobtrusive*");
- cssOrScriptFileSetOrdering.Files.Add("~/Scripts/jquery.validate*");
-
-
- bundles.FileSetOrderList.Add(cssOrScriptFileSetOrdering);
-
- var styleBundle = new Bundle("~/Content/css");
- styleBundle.Include("~/Content/*.css");
- bundles.Add(styleBundle);
-
-
- var scriptBundle = new Bundle("~/bundles/jquery");
- scriptBundle.Include("~/Scripts/*.js");
- //add the scriptBundle object to the bundles Collection
- bundles.Add(scriptBundle);
-
- #endregion
- Create a function with the name AddDefaultFileOrderings that is basically a static function of the BundleCollection class. The following would be the code snippet.
- public static void RegisterBundles(BundleCollection bundles)
- {
- #region BundleFileSetOrdering
-
- bundles.FileSetOrderList.Clear();
-
- var styleBundle = new Bundle("~/Content/css");
- styleBundle.Include("~/Content/*.css");
-
- bundles.Add(styleBundle);
-
- AddDefaultFileOrderings(bundles.FileSetOrderList);
-
- var scriptBundle = new Bundle("~/bundles/jquery");
- scriptBundle.Include("~/Scripts/*.js");
-
-
- bundles.Add(scriptBundle);
-
-
- #endregion
- }
-
- public static void AddDefaultFileOrderings(IList<BundleFileSetOrdering> list)
- {
- BundleFileSetOrdering cssOrScriptFileSetOrdering = new BundleFileSetOrdering("script");
- cssOrScriptFileSetOrdering.Files.Add("~/Content/reset.css");
- cssOrScriptFileSetOrdering.Files.Add("~/Content/normalize.css");
- cssOrScriptFileSetOrdering.Files.Add("~/Content/Site.css");
- cssOrScriptFileSetOrdering.Files.Add("~/Content/MyStyle.css");
- cssOrScriptFileSetOrdering.Files.Add("~/Scripts/jquery-{version}.js");
- cssOrScriptFileSetOrdering.Files.Add("~/Scripts/jquery.unobtrusive*");
- cssOrScriptFileSetOrdering.Files.Add("~/Scripts/jquery.validate*");
- list.Add(cssOrScriptFileSetOrdering);
- }
Updated _Layout.cshtml file.
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width" />
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @* <link rel="Stylesheet" type="text/css" href="@Styles.Url("~/Content/css")" />*@
- @*@Scripts.Render("~/bundles/modernizr")*@
- </head>
- <body>
- @RenderBody()
- @* <script type="text/javascript" src="@Scripts.Url("~/bundles/jquery")"></script>*@
- @Scripts.Render("~/bundles/jquery")
- @* <script type="text/javascript">
- //checking for the jquery is loaded or not. You can also cheche the same by using the below commented line
- //if(typeof($)=='function') && typeof(jQuery)=='function')
- if (typeof jQuery == undefined) {
- //creating the script element
- var e = document.createElement("script");
- //setting the src attribute of the script to load dynamically
- e.src = '@Url.Content("~/Scripts/jquery-1.7.1.min.js")';
- //settting the type of the script
- e.type = 'text/javascript';
- //appending the newly created script element in the header section of the html page
- document.getElementByTagName("head")[0].appendChild(e);
- }
- </script>*@
- @RenderSection("scripts", required: false)
- </body>
- </html>
4. ResetAll(): You can reset all the ordering of bundling using the ResetAll() function of the BundleCollection class. This will remove any custom order that has been applied to the BundleCollection class. The only thing that you need to write is the following line of code in the BundleConfig.cs file.