Minify inline JavaScript in ASP.NET MVC with WebGrease

ASP.NET 4.5 comes with great new feature to make web faster – JavaScript bundling and minification. It allows to bundle multiple js file into one and minfiy them.

This works great for external JavaScript files but what about inline scripts? There is library BundleMinifyInlineJsCss to do this but it has two downsides:

  1. It has to parse whole page to find all scripts so some unncessary overhead is added.
  2. It bundles all inline scripts into single script before body closing tag and does not respect script dependecies on external scripts.

Here is solution to minify inline JavaScript that work with ASP.NET MVC Razor View engine with less overhead and more granular control.

  1. If you are using System.Web.Optimization and Bundles you are all set  beacuse it comes with WebGrease.dll that we will use for minification otherwise you can get it here – WebGrease NuGet package.
  2. We will use this helper
    using Microsoft.Ajax.Utilities;
    using System;
    namespace System.Web.Mvc
        public class HtmlHelperExtensions
            public static MvcHtmlString JsMinify(
                this HtmlHelper helper,
                Func<object, object> markup)
                string notMinifiedJs =
                    (markup.DynamicInvoke(helper.ViewContext) ?? "").ToString();
                var minifier = new Minifier();
                var minifiedJs = minifier.MinifyJavaScript(notMinifiedJs, new CodeSettings
                    EvalTreatment = EvalTreatment.MakeImmediateSafe,
                    PreserveImportantComments = false
                return new MvcHtmlString(minifiedJs);
  3. And inside your Razor view:
     <script type="text/javascript">
            window.Yk = window.Yk || {};
            Yk.__load = [];
            window.$ = function (f) {
  4. When view is rendered you get minified version:
        <script type="text/javascript">

You can fine tune minification using CodeSettings object passed to minifier. As far as performace in concerned on average development machine it usually takes less that 1 millesecond to minify single inline script.