How to compress webpages with gzip using global.asax

June 07, 2011 - 12:46

Almost all modern webbrowsers support gzip compression, and its recommended to use this to reduce the size of webpages which in turn can dramatically reduce the download time.

The gzipping of pages is done at the server after the page is rendered and sent back to the clients browser. There are a number of ways to do this, but i find the easiest way to do this is to add a global.asax file. By placing this file into the websites root directory gzip can be enabled for some websites and not for others, which may be desirable.

To do this create a global.asax file in the root of your websites directory and copy the contents below.

<%@ Application Language="VB" %>

<script runat="server">

Protected Sub Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
if ("" & Request.Headers.Get("Accept-Encoding")).ToLower().Contains("gzip") then
Response.Filter = New System.IO.Compression.GZipStream(Response.Filter, System.IO.Compression.CompressionMode.Compress)
Response.AppendHeader("Content-Encoding", "gzip")
end if
End Sub

</script>


What this does is check to see if the browser is sending information that it understands the gzip encoding, and if it does then the content is encoded using gzip. If no "Accept-Encoding" header is sent to the server then a standard uncompressed webpage is returned.

Please note that this will only compress your aspx files, and any css or html pages will not be compressed.



© 2011 simplevb.net