7/22/2011

Combine and minifier javascripts file using Microsoft AJAX Minifier library

Loading javascript/ scc files in your web app have some issue:
- Amount of data
- Sequence of files, some time process is broken because one javascript file is not loaded
Using AJAX Minifier library help us solve them:



public class JavascriptHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string file = context.Request["file"];
            var settings = new CodeSettings
            {
                MinifyCode = true,
                OutputMode = OutputMode.SingleLine,
                CollapseToLiteral = true,
                CombineDuplicateLiterals = true,
                EvalTreatment = EvalTreatment.MakeAllSafe,
                IndentSize = 10000,
                InlineSafeStrings = true,
                LocalRenaming = LocalRenaming.CrunchAll,
                MacSafariQuirks = true,
                PreserveFunctionNames = true,
                RemoveFunctionExpressionNames = true,
                RemoveUnneededCode = true,
                StripDebugStatements = true
            };
            var min = new Minifier();
            var path = context.Request.MapPath("/Scripts/" + file);
            StreamReader sr = new StreamReader(path);
            var minifieredData = min.MinifyJavaScript(sr.ReadToEnd());
            context.Response.ContentType = "text/javascript";
            context.Response.Write(minifieredData);
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
 
In client side, we just add script reference to our system to load javascript files.

<script src="JavascriptHandler.ashx?file=IntegerHelper.js" type="text/javascript"></script>


We can also use AJAX Minifier library to get css files.

No comments:

Post a Comment