Thursday, 22 December 2011

YUI: Compressing JavaScript and CSS files with Ant

The YUI Compressor is JavaScript and CSS minifier designed to be 100% safe and yield a higher compression ratio than most other tools.

  1. First of all you should download latest version of yuicompressor
  2. If you want to run it in eclipse with ant,you need ant-task
  3. You should edit your ant build.xml file, and add this lines of code:

<project name="test">
<property name="web.dir" value="WebContent"/>
    <property name="input.dir" value="${web.dir}/js"/>
    <property name="output.dir" value="${web.dir}/jscompressed"/>
    <target name="clean_compressed_js" description="Clean output directories">
                <fileset dir="${output.dir}">
                    <include name="*.js"/>
    <taskdef name="yuicompress" classname="">
            <pathelement path="${web.dir}/WEB-INF/lib/yuicompressor-2.4.7.jar" />
            <pathelement path="${web.dir}/WEB-INF/lib/yui-compressor-ant-task-0.5.jar" />
            <pathelement path="${web.dir}/WEB-INF/lib/rhino-1.6R7.jar" />


    <target name="compress_javascript" depends="clean_compressed_js">
        <echo>Compressing files</echo>
        <yuicompress munge="yes"  preserveallsemicolons="yes" toDir="${output.dir}" fromDir="${input.dir}" csssuffix=".css" jssuffix=".js" >
                <include name="*.js"/>

PS: Next step of optimisation should be creating gzip archive with compressed files, if your server support it

Also tools for testing your web-site speed:


  1. Awesome link.. I was searching implementation of YUI in build.xml from last 2 days. And every other link is complex and doesn't work even. But this is short, self descriptive and perfect link. Thanks for this post

  2. yeah but why rhino-1.6R7.jar and yui-compressor-ant-task-0.5.jar are using this tool please help i stuck in this.

    1. It is some dependent libraries, waht is your problem?

    2. i am getting the following exception while minifying the js files java.lang.IllegalAccessError: tried to access class org.mozilla.javascript.DefaultErrorReporter from class org.mozilla.javascript.CompilerEnvirons

      please help..,,thanks in advance

    3. it is somth wrong with your rhino maybe it is not included or dublicated see here