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">
            <delete>
                <fileset dir="${output.dir}">
                    <include name="*.js"/>
                </fileset>
            </delete>
        </target>
     
    <taskdef name="yuicompress" classname="net.noha.tools.ant.yuicompressor.tasks.YuiCompressorTask">
        <classpath>
            <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" />

        </classpath>
    </taskdef>   
    

    <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"/>
        </yuicompress>
    </target>
</project>

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

References:
http://developer.yahoo.com/yui/compressor/
http://webo.in/articles/habrahabr/112-minify-combine-javascript-troubles/
Also tools for testing your web-site speed:
http://loads.in/
http://tools.pingdom.com/
http://gtmetrix.com/
https://developers.google.com/pagespeed/

7 comments:

  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

    ReplyDelete
  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.

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

      Delete
    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

      Delete
    3. it is somth wrong with your rhino maybe it is not included or dublicated see here https://issues.liferay.com/browse/LPS-1822

      Delete