Saturday, June 1, 2013

Sitecore CSS/JS Media Items Minfier

As suggested by Google, minification of CSS and JS resources improves the performance of websites. Minification can save many bytes of data and speed up downloading, parsing, and execution time.

In Sitecore CMS, for JS and CSS resources present in media library, it is a good idea to keep minified versions in live environment and original uncompressed versions in development/authoring environment.

Media Items Minifier Module

I have created a media items minifier module for Sitecore which will minify any CSS/JS media item when published. Media items will be minified only in target environment, items in source environment will not be impacted. It makes use of YUICompressor for minifying CSS/JS resources.

This module is basically an event handler for Sitecore's publish:itemProcessed event which is triggered after an item is published. 

After installing this module a MediaItemsMinifier.config file is created in /Website/App_Config/Include folder. It contains below configuration:

 <configuration xmlns:patch="">  
   <events timingLevel="custom">  
    <event name="publish:itemProcessed">  
     <handler type="MediaItemsMinifier.ItemProcessedEventHandler, MediaItemsMinifier" method="OnItemProcessed">  

In <databases> node list of comma separated target database names can be given in which media items should be minified.

Whenever an item is published, this module first check whether target database name is part of <databases> node or not. Then it verifies if item is published and it is CSS/JS media item.
When the published item is a CSS/JS media item, it performs following actions:
  1. Get original contents using GetMediaStream method of MediaItem.
  2. Compress the contents using YUICompressor.
  3. Edit the target media item to upload minified version.
This way media items are minified only in target environments when they are published from source environment.

To view the source code and download the Sitecore package visit Media Items Minifier at github.

Update: Media Items Minifier module is now available at Sitecore Marketplace.

No comments:

Post a Comment