Minify Html output of ASP.NET Application
Asked Answered
I

7

37

What are the ways by which we can reduce the size of the HTML Response sent by an asp.net application?

I am using Controls which are not owned by me and it produces output with white spaces. I am interested in Minifying the entire HTML output of the page just like how google does (View source www.google.com) to improve the timing.

Is there any Utility classes available for ASP.NET which can do this stuff for me?

Incogitant answered 31/10, 2008 at 21:25 Comment(0)
W
32

There is no need to do it at run time. Because it can be done at compile time.

Details: http://omari-o.blogspot.com/2009/09/aspnet-white-space-cleaning-with-no.html

Walleyed answered 27/1, 2010 at 13:43 Comment(7)
Great link. This was my solution for #7121871Questionary
How did you apply this in the project? Sorry for my ignorance, but I can't make it work.Pentagram
@ryan What errors do you get? Have you specified pageParserFilterType in web.config?Walleyed
I got it :-) I just have to add <pages pageParserFilterType="Omari.Web.UI.WhiteSpaceCleaner, WhiteSpaceCleanerForWebFormsAndMVC3" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"> and set debug = false.Pentagram
While the linked blog post is still there, the link to the code on the blog post is now broken.Farthing
There is a similar example of using a PageParserFilter here gist.github.com/NightOwl888/c1f0a558d69f82dedfefExpound
and another example of using the PageParserFilter here sergeyakopov.com/…Expound
C
20

Try HTTP module as described here: http://madskristensen.net/post/a-whitespace-removal-http-module-for-aspnet-20

Contraoctave answered 31/10, 2008 at 21:30 Comment(2)
Broken url, project seems no longer valid.Coahuila
Note: This only works if the request ends with .aspx but you can modify the codeLyford
B
10

For Microsoft .NET platform there is a library called the WebMarkupMin, which produces the minification of HTML code. For each ASP.NET framework has its own module:

Documentation is available at - http://webmarkupmin.codeplex.com/documentation

Berm answered 16/9, 2014 at 11:54 Comment(4)
WebMarkupMin is not able to minify razor code, but it can minify the output HTML code.Berm
so how do you use it? I see you can download and install for asp.net web forms but after that what? nuget.org/packages/WebMarkupMin.AspNet4.WebFormsAxilla
WebMarkupMin moved to GitHub. If you have used old versions of WebMarkupMin, then I recommend to first read “How to upgrade applications to version 2.X” section of the documentation.Berm
@Axilla You need to read “ASP.NET Extensions”, “ASP.NET 4.X Extensions” and “WebMarkupMin: ASP.NET 4.X Web Forms” sections of the documentation.Berm
M
6

I want to comment on Thorn's suggestion (but I'm new to stack overflow).

  1. The linked code (omari-o.blogspot.com) doesn't support MVC4, and although the code is open source it cannot easily be upgraded because of braking changes between MVC3 and MVC4.

  2. There might be whitespaces written to the http result at runtime, only the developer of the actual site can know that. Thus static minification of template files (aspx) is not foolproof at all. Dynamic minification, which is suggested by gius, should be used to guarantee that whitespaces are removed correctly, and unfortunately this will incur a runtime computation cost. If code dynamically writes spaces to the output, it will have to be removed dynamically.

Misgive answered 22/7, 2013 at 7:59 Comment(0)
P
3

The accepted answer does not work with MVC 4, so here is a similar lib that minifies at build-time https://github.com/jitbit/HtmlOptimizerMvc4

Philip answered 20/11, 2014 at 1:7 Comment(2)
did you have any problems with VS stopping to recognize @model in your views ?Tojo
Why did you post a forked version without any modifications?Hanus
T
2

Just adding another option I do not see listed here, which is the one I was recommended using:

Html minifier command line tool

Usage: here and here

There is an issue, however, with this tool: it leaves single line (//) comments, and it causes problems for Razor parsing, since a single line comment placed within a C# block like the following:

@{
  ... 
  ...
  // anything
  ...
}

will cause the minification output rest of the line, from this point on, to be ignored by the Razor parser, which will thus raise an error stating there it could not find the closing "}" for the block.

My workaround for this issue was to completely removing these comments from the output. This way it works. To do that, simply remove the RegexOptions.SingleLine from line 145:

htmlContents = Regex.Replace(htmlContents, @"//(.*?)\r?\n", ""/*, RegexOptions.Singleline*/);
Tojo answered 24/2, 2015 at 9:54 Comment(1)
This issue should be fixed in the latest version - github.com/deanhume/html-minifierAvuncular
R
0

Use this function in behind of master page or web form page, before Page_Load event:

protected override void Render(HtmlTextWriter writer)
{
    if (this.Request.Headers["X-MicrosoftAjax"] != "Delta=true")
    {
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"<script[^>]*>[\w|\t|\r|\W]*?</script>");
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        System.IO.StringWriter sw = new System.IO.StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        base.Render(hw);
        string html = sb.ToString();
        System.Text.RegularExpressions.MatchCollection mymatch = reg.Matches(html);
        html = reg.Replace(html, string.Empty);
        reg = new System.Text.RegularExpressions.Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}|(?=[\r])\s{2,}");
        html = reg.Replace(html, string.Empty);
        reg = new System.Text.RegularExpressions.Regex(@"</body>");
        string str = string.Empty;
        foreach (System.Text.RegularExpressions.Match match in mymatch)
        {
            str += match.ToString();
        }
        html = reg.Replace(html, str + "</body>");
        writer.Write(html);
    }
    else
    {
        base.Render(writer);
    }
}
Roter answered 7/11, 2023 at 16:46 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.