Remove whitespace safely at runtime

May 9, 2006

A couple a months ago, I wrote how to remove whitespace from an ASP.NET page. However, the whitespace removal was to extreme for most websites. It mangled with the HTML to such an extent that only very simple websites could use it without damaging their code.

I’ve just finished a more complex website and therefore had to make some changes to my original whitespace removal method. Otherwise, the JavaScript wouldn’t work including the postbacks.

To make it work, simply paste this method into your .aspx or master page.

protected override void Render(HtmlTextWriter writer)
{
   using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
   {
      base.Render(htmlwriter);
      string html = htmlwriter.InnerWriter.ToString();

      html = Regex.Replace(html, @"(?<=[^])\t{2,}|(?<=[>])\s{2,3}(?=[<])|(?<=[>])\s{2,3}(?=[<])|(?=[\n])\s{2,3}", String.Empty);
      html = Regex.Replace(html, @"[\f\r\t\v]?([\n\xFE\xFF/{}[\];,<>*%&|^!~?:=])[\f\r\t\v]?", "$1");
      html = html.Replace(";\n", ";");

      writer.Write(html.Trim());
   }
}

I’ve calculated that the total HTML file size will be reduces by 10-13 %. To see an example of this method, just visit www.wulffmorgenthaler.com and view the source.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (4) -

 Sachman Bhatti
Sachman Bhatti
11/30/2006 6:25:27 PM #

Is there any safe way to implement this with the CompressionModule?

I tried calling WhiteSpaceFilter before the compress, so Stream strWhiteSpace = new WhitespaceFilter(app.Response.Filter); and then app.Response.Filter = new GZipStream(strWhiteSpace, CompressionMode.Compress); (or the deflate depending on the if)


but I get a whole bunch of weird stuff in the output

 Sachman Bhatti
Sachman Bhatti
11/30/2006 6:27:33 PM #

Oops sorry, I thought this was the module entry.  Sorry about that, and yah it mangled mine. Smile

Matt Tester
Matt Tester New Zealand
11/24/2007 10:58:18 PM #

This works great except when the page contains an UpdatePanel. When it does, you get a parse error from the browser with the response. I haven't pinned down what the real cause is (the error message doesn't help!), but can put any results here.

bobac
bobac Ukraine
12/1/2007 5:43:36 AM #

you can fight this error by adding this line
if (Request["HTTP_X_MICROSOFTAJAX"] == null)

but it will not get rid you of the problem.
there will be no errors but an UpdatePanel
still doesn't work. Frown

Pingbacks and trackbacks (2)+

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.