Monday, August 8, 2011

How to minify Javascript, CSS files automatically in YII Framework

We are going to reduce the HTTP calls for resources files by merging several resources files into a single (or more) files, so that the application load faster. E Client Script can automatically detect the required list of files, and generate a unique filename hash, so boldly ease of use.

CSS Files:

CSS files are merged based on there media attribute, background images with a relative path in file can also be displayed correctly.

Script files:

Script files are merged based on their position, If you use the 'CClientScript::POS_HEAD' you will end up with a single file for all the script files you've used on that page.

If you use 'CClientScript::POS_HEAD' and 'CClientScript::POS_END' for example then you'll end up with two files for each page on that request, Since those resources are located in different positions.

Add the following code to components array in protected/config/main.php

Add to configuration:
First you have to download EClientScript extension

 'clientScript' => array(
            'class' => 'ext.minify.EClientScript',
            'combineScriptFiles' => true,
            'combineCssFiles' => true,
            'optimizeCssFiles' => true,
            'optimizeScriptFiles' => false,

Then you'd use the regular 'registerScriptFile' & 'registerCssFile' methods as normal and the files will be combined automatically

No comments: