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 yahoo for 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.

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Twitter

Leave a Reply