Monday, June 15, 2009

Minifying CSS and JS with Yahoo YUI Compressor

In my previous blog post I explained how to use Ant to concatenate javascript and css files in a way to minimize the number of http requests.
Another recommendation by yahoofor building high performance websites is to minify JS and CSS files. The reasoning is that the smaller the size of the javascript/css, the less time it takes for them to be interpreted.

Yahoo provides a great utility - yahoo yui compressor that minifies both javascript and css.

We can therefore improve our build script and add the following task:


<!-- this compresses all the css and js in the static folder -->
<target name="js.minify">
<property
name="yui-compressor.jar"
location="lib/yuicompressor-2.4.2.jar" />
<property
name="yui-compressor-ant-task.jar"
location="lib/yui-compressor-ant-task-0.3.jar" />

<path id="task.classpath">
<pathelement location="${yui-compressor.jar}" />
<pathelement location="${yui-compressor-ant-task.jar}" />
</path>

<taskdef
name="yui-compressor"
classname="net.noha.tools.ant.yuicompressor.tasks.YuiCompressorTask">

<classpath refid="task.classpath"/>
</taskdef>

<yui-compressor warn="false" charset="UTF-8" jsSuffix="-min.js" cssSuffix="-min.css" fromdir="${build.dir}/static" todir="${build.dir}/static">
<include name="**/*.js" />
<include name="**/*.css" />
</yui-compressor>


<move todir="${build.dir}/static" includeemptydirs="false">
<fileset dir="${build.dir}/static">
<include name="**/*-min.css"/>
</fileset>
<mapper type="glob" from="*-min.css" to="*.css"/>
</move>
<move todir="${build.dir}/static" includeemptydirs="false">
<fileset dir="${build.dir}/static">
<include name="**/*-min.js"/>
</fileset>
<mapper type="glob" from="*-min.js" to="*.js"/>
</move>

</target>


First we copy all the javascript and css files to the build/static folder and then we use yahoo compressor to minify all the files in this directory.

Click here to download an example.

2 comments:

Storm Belle said...

Hi Armindo,

Thanks for the code snippet.I am fairly new to ant and I want to use the yui-compressor-ant-task.

Mine is a very basic question:where do I put the yui-compressor-ant-task-0.4.jar file?

I have placed it under my /lib directory and have included it in my build path - but my Eclipse IDE warns me with the message

taskdef class net.noha.tools.ant.yuicompressor.tasks.YuiCompressorTask cannot be found

I have set the location as follows

location="${lib.dir}/yui-compressor-ant-task-0.4.jar"

where lib.dir is the main lib directory in my set up

Everything else is the same as in your post.

Any help you can give me is much appreciated.

-Stormbelle

Armindo Cachada said...

Hi,

Did you include all the necessary jars in your eclipse build path?
The error message you see, is it the message that you get when you try to run the ant build file? Or the message that you see in the eclipse ide list of problems?

 
Software