How to compress SVG images from the Sitecore media library

This blog post is long overdue. The code was written some time last year when I started my still on-going fight with Google Page Speed.

When Sitecore deliver svg files from the media library there is no out-of-the-box approach for gzipping the media content and setting the Content-encoding response header to gzip.

Gzipping the svg media content

First we need to gzip the media content.

To do this we insert the following processor into the end of the getMediaStream pipeline.

You will notice that we call a service class IsCompressableService which checks if the media stream should be compressed.

This service reads a comma separated line from config:

Now the media stream is gzipped, so we need to tell the browsers that the content is gzip encoded so they can understand what it is we are sending them.

Setting the Content-encoding response header

To do this we need to hook into the otherwise hidden event called media:request as I’ve also shown in this post.

We first get the media item which is being requested and then we check using the file extension if the content should be compressed. If so we add Content-encoding: gzip as a response header.

The configuration for hooking into the event looks like this.

That was it. The same code can gzip any other text based content such as js, css, xml etc. but it is better to use IIS dynamic compression for this. If anyone have a tip on how to configure IIS 7 / 7.5 to dynamic compress svg files please share as long as it doesn’t imply changing the mime type to text/xml which is a terrible hack. It is possible to edit the applicationhost.config and set the mime-type here but this require you to have permissions (and time) to do this on all servers in the environment.

Please drop me a mail or a  comment if you would like me to share the code as a project or a MarketPlace module.

Anders Laub

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 has been nominated a Sitecore Technical MVP three years in a row for 2014, 2015 and 2016. Anders is now working as a Sr. Solutions Architect at Sitecore in Copenhagen.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
Website