I wanted to make a quick way to make every page of our new sites smaller. I was thinking we'll have to start formatting all of our HTML but that would make it nearly unreadable for us to develop with and then I remembered the Filter property of the HttpResponse object so I started investigating and found this article http://www.aspalliance.com/robertb/articles.aspx?articleId=6&print=true by Robert Boedigheimer and I was on my way.
Here is what I came up with to take out all tabs and new line feeds. After testing pages were definately smaller and rendering was quicker. If someone has a better way please let me know:
Implementation
Implementation is done application wide in my base page class' OnInit method which all webforms inherit from:
this
.Response.Filter = new Base.ResponseFilter(Response.Filter);
Response Filter Class File
using System.Text;
using System;
using System.Text.RegularExpressions;
using System.IO;
namespace CodeJunkies.Base {
public class ResponseFilter : Stream {
#region properties
Stream responseStream;
long position;
StringBuilder html = new StringBuilder();
#endregion
#region constructor
public ResponseFilter(Stream inputStream) {
responseStream = inputStream;
}
#endregion
#region implemented abstract members
public override bool CanRead {
get { return true; }
}
public override bool CanSeek {
get { return true; }
}
public override bool CanWrite {
get { return true; }
}
public override void Close() {
responseStream.Close();
}
public override void Flush() {
responseStream.Flush();
}
public override long Length {
get { return 0; }
}
public override long Position {
get { return position; }
set { position = value; }
}
public override long Seek(long offset, System.IO.SeekOrigin direction) {
return responseStream.Seek(offset, direction);
}
public override void SetLength(long length) {
responseStream.SetLength(length);
}
public override int Read(byte[] buffer, int offset, int count) {
return responseStream.Read(buffer, offset, count);
}
#endregion
#region write method
public override void Write(byte[] buffer, int offset, int count) {
// string version of the buffer
string sBuffer = System.Text.UTF8Encoding.UTF8.GetString(buffer, offset, count);
// end of the HTML file
Regex oEndFile = new Regex("</html>", RegexOptions.IgnoreCase);
if (oEndFile.IsMatch(sBuffer)) {
// Append the last buffer of data
html.Append(sBuffer);
string tempResponse = html.ToString();
string newBuffer = Regex.Replace(tempResponse, "\t", string.Empty );
newBuffer = Regex.Replace(newBuffer, "\n", string.Empty );
newBuffer = Regex.Replace(newBuffer, "\r", string.Empty );
newBuffer = Regex.Replace(newBuffer, "<!--", "<!-- \n" );
newBuffer = Regex.Replace(newBuffer, "// -->", "// --> \n" );
tempResponse = newBuffer;
byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(tempResponse);
responseStream.Write(data, 0, data.Length);
}
else {
html.Append(sBuffer);
}
}
#endregion
}
}