Submit Your Article
Home Articles News Tutorials Videos Add An Article
Topics: Design Photoshop Programming PHP CSS Java Database Web Development Javascript Ajax
– Close + Open

Find Out More About DevWebPro!

Sign up for the newsletter


» Terms & Conditions

Welcome to the New DevWebPro!

DevWebPro Includes:
  Hundreds Of Tutorials   Developer News
  Unique Gadget Videos   Tons of Topics to Discuss
  Expert Advice   We Will Publish Your Articles

Removing Whitespace From Your Pages With ASP.NET

By: Mads Kristensen
Monday, October 22nd, 2007
Text: Decrease Font Size Increase Font Size | Print Print Article | Share: Delicious Digg StumbleUpon Post to Twitter Post to Facebook

Ok, this is not new. I’ve also written about this a few times in the past.

The thing is that removing whitespace is a very tricky discipline that is different from site to site. At least that was what I thought until very recently.

For some unexplained reason I started working on a little simple method to remove whitespace in a way so it works on all websites without breaking any HTML. Maybe not unexplained since I’ve written about it so many times that it would seem I got a secret obsession.

Obsession or not, here is the code I ended up with after a few hours of hacking. Just copy the code onto your base page or master page and watch the magic.

private static readonly Regex REGEX_BETWEEN_TAGS = new Regex(@">s+<", RegexOptions.Compiled);

private static readonly Regex REGEX_LINE_BREAKS = new Regex(@"ns+", RegexOptions.Compiled);

/// <summary>

/// Initializes the <see cref="T:System.Web.UI.HtmlTextWriter"></see> object and calls on the child

/// controls of the <see cref="T:System.Web.UI.Page"></see> to render.

/// </summary>

/// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"></see> that receives the page content.</param>

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_BETWEEN_TAGS.Replace(html, "> <");

      html = REGEX_LINE_BREAKS.Replace(html, string.Empty);

      writer.Write(html.Trim());

    }

}

Remember that whitespace removal speeds up rendering in especially IE and reduces the overall weight of your page.

Comments

Topics: ,

About the Author:
Mads Kristensen currently works as a Senior Developer at Traceworks located in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in 2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and web services in his daily work as well. A true .NET developer with great passion for the simple solution. http://www.madskristensen.dk/
DevWebPro is an iEntry Network ® publication - © 1998-2010 All Rights Reserved