In a normal webpage there is a lot of whitespace. Compressed requests and responses always increase the performance of sites. Nowadays, almost all latest browsers support compression.  By getting free of all the extra whitespace in the HTML you can save up to 25% of the total weight of the page in kilo bytes and make rendering in the browser faster.

Example: Retrieve the HTML before sending it to the browser

This can be done in either the Render method of a Page or MasterPage or it can be done in an HttpModule. In ASP.NET MVC you have no Render method to override and you need to remove the whitespace from an HttpModule.

protected override void Render(HtmlTextWriter writer)
  using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
    string html = htmlwriter.InnerWriter.ToString();
    // Trim the whitespace from the 'html' variable
Example: Remove whitespace

Here we need to use two regular expressions to identify the areas of whitespace that are safe to remove.

private static readonly Regex RegexBetweenTags = new Regex(@">(?! )\s+", RegexOptions.Compiled);

private static readonly Regex RegexLineBreaks = new Regex(@"([\n\s])+?(?<= {2,})<",RegexOptions.Compiled);

This method uses the two regular expressions to remove any whitespace from a string of HTML.

public static string RemoveWhitespaceFromHtml(string html)
  html = RegexBetweenTags.Replace(html, ">");
  html = RegexLineBreaks.Replace(html, "<");
  return html.Trim();

You can be remove whitespaces by using “Bundling and Minification” in ASP.NET project. You can read and see demo on “Bundling and Minification” from below URL




  Modified On Sep-18-2014 01:24:09 PM

Leave Comment