Sunday, 12 July 2015

Bundling and minification in Sitecore MVC

Leave a Comment
This is a quick blog post on how to implement bundling and minification in Sitecore MVC project.  During development phase, it is always good to have multiple Javascripts and CSS files for better readability and maintainability of code.  But multiple Javascripts and CSS files degrade the performance of production website and also increase the load time of webpages as it requires multiple HTTP requests from browser to server.  Bundling and minification reduce the size of Javascript and CSS files and bundle multiple files into a single file and make the site perform faster by making fewer HTTP requests. Below steps explain how to implement bundling and minification for Sitecore MVC project:
  1. Add Microsoft ASP.NET Web Optimization Framework to your solution from nuget or run the following command in the Package Manager Console to install Microsoft ASP.NET Web Optimization Framework.
    PM> Install-Package Microsoft.AspNet.Web.Optimization
  2. Create your CSS and Javascript bundles in “BundleConfig” class under App_Start folder and add reference of "System.Web.Optimization" namespace.
    public class BundleConfig
        {
            public static void RegisterBundles(BundleCollection bundles)
            {
                //js bundling using wildcard character *
                bundles.Add(new ScriptBundle("~/bundles/js").Include("~/assets/js/*.js"));
    
                //css bundling using wildcard character *
                bundles.Add(new StyleBundle("~/bundles/css").Include("~/assets/css/*.css"));
            }
        }
  3. Register bundle in the Application_Start method in the Global.asax file. If you are using Multi-site instance of Sitecore MVC then recommend way to implement bundling logic is by creating a new processor into the initialize pipeline. This blog explains how to do configure it using pipeline processor.
     protected void Application_Start(object sender, EventArgs e)
            {
                BundleConfig.RegisterBundles(BundleTable.Bundles);
            }
  4. Enable bundling and minification by setting the value of the debug attribute in the compilation element to false in web.config.
    <compilation defaultLanguage="c#" debug="false" targetFramework="4.5">
    </compilation>
    
    We can override the value of the debug attribute in code by using EnableOptimizations property of the BundleTable class.
    protected void Application_BeginRequest(object sender, EventArgs e)
            {
                EnableBundleOptimizations();
            }
    
            private void EnableBundleOptimizations()
            {
                string debugMode = Request.QueryString["debug"];
                if (!string.IsNullOrEmpty(debugMode) && string.Equals(debugMode, "true", StringComparison.InvariantCultureIgnoreCase))
                {
                    BundleTable.EnableOptimizations = false;
                }
                else
                {
                    BundleTable.EnableOptimizations = true;
                }
            }
    Here in Application_BeginRequest method of Global.asax I am calling one custom method EnableBundleOptimizations() which sets the value of EnableOptimizations property to true or false based on value of querystring “debug”. Main idea behind this logic is that we can check/debug CSS or Javascript file on production by passing querystring parameter debug as true. 
  5. Replace Javascripts and CSS references in layout or rendering view with below code:
    @Styles.Render("~/bundles/css")
    @Scripts.Render("~/bundles/js")
    
  6. In web.config set an ignore url prefix for your bundle so that Sitecore won’t try to resolve the URL to the bundle. Update setting IgnoreUrlPrefixes according to your bundle name:
    <setting name="IgnoreUrlPrefixes" value="/sitecore/default.aspx|/trace.axd|/webresource.axd|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.DialogHandler.aspx|/sitecore/shell/applications/content manager/telerik.web.ui.dialoghandler.aspx|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.SpellCheckHandler.axd|/Telerik.Web.UI.WebResource.axd|/sitecore/admin/upgrade/|/layouts/testing|/bundles/js|/bundles/css"/>
  7. Now compile your solution and verify that bundling and minification is enabled by checking view source of webpage.
    Pass querystring as debug=true in url and now verify view source of webpage. Bundling and minification is not enabled. This enables us to debug Javascript and CSS files in production website.
Comments and suggestions are most welcome. Happy coding!

0 comments :

Post a Comment