blog

Home / DeveloperSection / Blogs / Compress or Remove WhiteSpace before deploying in Asp.NET MVC

Compress or Remove WhiteSpace before deploying in Asp.NET MVC

AVADHESH PATEL14654 06-Mar-2013

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()))
  {
    base.Render(htmlwriter);
    string html = htmlwriter.InnerWriter.ToString();
    // Trim the whitespace from the 'html' variable
    writer.Write(html);
  }
}
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

http://www.mindstick.com/Articles/2d3da74a-94da-45fe-b361-97263cd725f2/?Bundling%20and%20Minification%20in%20ASP%20NET%20MVC%204

 

 

 


Updated 18-Sep-2014
Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By