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

Compress or Remove WhiteSpace before deploying in Asp.NET MVC


ASP.NET MVC ASP.NET MVC 
Ratings:
1 Comment(s)
 7649  View(s)
Rate this:

Compress or Remove WhiteSpace before deploying in Asp.NET MVC

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

 

 

 


Minify html with aspnet mvc 4-razor

By Jacob Phan on   2 years ago
I have an alternative solution here http://jacob-phan.blogspot.com/2014/06/minify-html-with-aspnet-mvc-4-razor.html

I hope it's useful for you

Don't want to miss updates? Please click the below button!

Follow MindStick