Minify HTML page using simple c# code

Minify HTML page using simple c# code

Magnification is very important think when looking for batter performance. In order to do this in asp dot net page you just need to follow the steps.

create regex variable as below.

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

First will remove the space between less than () sign from the webpage.
Second will remove the new lines from the webpage.
After that we need to create method to use this variable as below.

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

After that we need to override render event of the page life cycle as below.

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

Hope it will help someone. I would like to have feedback and question from my blog reads, please post your comment and question in order to make it more useful. You can download code from here.

4 thoughts on “Minify HTML page using simple c# code

  1. Hello, How Can I avoid issues with JavaScript (inside ScriptManager)? If I use this minify JavaScript, it broken javascript inside UpdatePanel. For example If I need pop-ups on button click event (from code behind).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s