Skip to content

Instantly share code, notes, and snippets.

@michaelbramwell
Created March 3, 2016 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelbramwell/ca4d08382d87acab8340 to your computer and use it in GitHub Desktop.
Save michaelbramwell/ca4d08382d87acab8340 to your computer and use it in GitHub Desktop.
Html Uglify Module
public class HtmlUglifyFilter : Stream
{
private readonly Stream _responseStream;
private long _position;
public HtmlUglifyFilter(Stream inputStream)
{
_responseStream = inputStream;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override long Length
{
get { return 0; }
}
public override long Position
{
get { return _position; }
set { _position = value; }
}
public override void Flush()
{
_responseStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _responseStream.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _responseStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
_responseStream.SetLength(Length);
}
/// <summary>
/// Take various steps to minify html
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
public override void Write(byte[] buffer, int offset, int count)
{
char symbol;
bool betweenTags = true;
for (int i = 0; i < buffer.Length; i++)
{
symbol = Convert.ToChar(buffer[i]);
if (symbol == '>')
{
betweenTags = true;
_responseStream.WriteByte(buffer[i]);
continue;
}
if (betweenTags && char.IsWhiteSpace(symbol)) continue;
if (i > 1 && betweenTags && (Convert.ToChar(buffer[i - 1]) == ' '))
{
_responseStream.WriteByte(buffer[i - 1]);
}
if(symbol == '\n' || symbol == '\r') continue;
_responseStream.WriteByte(buffer[i]);
betweenTags = false;
}
}
}
public class HtmlUglifyModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.ReleaseRequestState += InstallHtmlMinifierFilter;
}
private void InstallHtmlMinifierFilter(object sender, EventArgs e)
{
if (HttpContext.Current.Response.ContentType != "text/html") return;
HttpContext.Current.Response.Filter = new HtmlUglifyFilter(HttpContext.Current.Response.Filter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment