My previous post showed how to gzip svg files served by the Sitecore media library. This is fine if all svg files reside in the media library but this is typical not the case.
In this post I will show how to gzip compress any svg files served by your ASP.NET solution. As I explained in my previous post the issue that I am attempting to solve is that IIS will not by default gzip svg files without a lot of configuration changes on server level.
The solution here is extremely simple and pragmatic. Simply implement a HttpModule and set the Response.Filter stream to a GZipStream.
GZip svg files
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public class SvgCompressionModule : IHttpModule { public void Init(HttpApplication application) { application.BeginRequest += ApplicationOnBeginRequest; } public void Dispose() { } private void ApplicationOnBeginRequest(object sender, EventArgs eventArgs) { var app = (HttpApplication) sender; if (app == null) return; var context = app.Context; if (!IsSvgRequest(context.Request)) return; context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress); context.Response.AddHeader("Content-encoding", "gzip"); } protected virtual bool IsSvgRequest(HttpRequest request) { var path = request.Url.AbsolutePath; return Path.HasExtension(path) && Path.GetExtension(path).Equals(".svg", StringComparison.InvariantCultureIgnoreCase); } } |
Then add the httpmodule to configuration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<configuration> ... <system.webServer> <modules> ... <add name="SvgCompressionModule" type="[NAMESPACE].SvgCompressionModule, [ASSEMBLY].SvgCompression" /> </modules> </system.webServer> ... <system.web> <httpModules> ... <add name="SvgCompressionModule" type="[NAMESPACE].SvgCompressionModule, [ASSEMBLY].SvgCompression" /> </httpModules> </system.web> </configuration> |
That is it. I hope this helps someone out there in their own personal fight with Google PageSpeed.
Anders Laub Christoffersen
Anders has been working with Sitecore for over a decade and has in this time been the lead developer and architect on several large scale enterprise solutions all around the world. Anders was appointed the title of Sitecore Technical MVP in 2014 and has been re-appointed the title every year since then.
- Web |
- More Posts
I tried to implement gzip for font in so many ways but nothing worked. You solution worked like magic. Hats of man…genius better solution with full control.
Thanks, I am glad you found it useful.
Thank you for sharing.. Works like a charm
This article is too helpful, thank you very much!!
Sir, you are my hero tonight… I was already screaming bloody murder
Thank you