Bundling and Minifying Inline Css and Js

        Introduction:


                    Application performance is the very important factor for an application success. Yahoo's Best Practices for Speeding Up Your Web Site is a great resource for increasing your application performance. Out of these practices, 'Putting Stylesheets at the Top', 'Putting Scripts at the Bottom' and 'Minifying(external and inline) JavaScript and CSS' are very important practices. Minifying inline css and js is also very important. From Yahoo Best Practices page 'In addition to minifying external scripts and styles, inlined <script> and <style> blocks can and should also be minified. Even if you gzip your scripts and styles, minifying them will still reduce the size by 5% or more. As the use and size of JavaScript and CSS increases, so will the savings gained by minifying your code '. So, in this article, I will show you how to minify and bundle(combine all css/js) your inline css/js.


        Description:


                    Open your ASP.NET application(WebForm or MVC) and install BundleMinifyInlineJsCss nuget package.


                     


                    Then register the response filter. If you are using WebForm, you can register response filter in a master page and if you are MVC, you can use register response filter in an action filter.  


    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Filter = new BundleAndMinifyResponseFilter(Response.Filter);
        }
    }
    public class BundleMinifyInlineCssJsAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Filter = new BundleAndMinifyResponseFilter(filterContext.HttpContext.Response.Filter);
        }
    }
    [BundleMinifyInlineCssJs]
    public class HomeController : Controller

                    Now just run your application. If a page view-source is,




                    After using the above response filter, it will become,


.



                    Note in the above screen the inline css moved to top, inline javascript moved to bottom and inline javascript/css is minified and bundled. 


        Summary:


                    In this article, I showed you how to you quickly and easily put all your inline css at the top, put all your js at bottom and minifying/bundle all your inline  javascript/css using a response filter. Hopefully you will enjoy this article too.



11 Comments

Comments have been disabled for this content.