Sunday, 22 June 2008

Compressing Javascript files in netbeans 6.1 - A solution

OK, I have a working solution for netbeans 6.1, I can not take any credit for this as my hunch was correct, it has been done before. I have adapted the work done by Philippe Mouawad and ANDREW GOMILKO using the YUI Compression tool as Ant Task so that it can be used with netBeans 6.1 web application projects.

To get automated javascript \and css files into your war files during the netbeans build process do the following :-

These two files need to go in your netbeans ant\lib folder, for my windows/netbeans 6.1 installation thats C:\Program Files\NetBeans 6.1\java2\ant\lib.

For web applications that you want to build with compressed js/css files add the folloing xml to the build.xml for the project, overiding the "-pre-dist" ant target which is not currently configured by default in netbeans.

<target name="-pre-dist">
<echo level="info" message="Compressing JavaScript and CSS files...." />
<path id="yuicompressor.classpath">
<fileset dir="${ant.home}/lib">
<include name="yuicompressor-2.3.5.jar"/>
</fileset>
</path>
<taskdef name="yuicompress"
classname="com.yahoo.platform.yui.compressor.YUICompressTask">
<classpath>
<path refid="yuicompressor.classpath"/>
</classpath>
</taskdef>
<yuicompress linebreak="300" warn="false" munge="no"
preserveallsemicolons="true"
outputfolder="${basedir}/${build.web.dir}" >
<fileset dir="${basedir}/web"
excludes="/ext-2.1/**/*.js" >
<include name="**/*.js" />
<include name="**/*.css" />
</fileset>
</yuicompress>
<echo level="info" message="Compression Complete" />
</target>
This will compress and copy the js and css files to the build directory before the war file is built and will thus be included in your war file.

Note there is a line in my example with an "exclude" for my ext-2.1 directory, the files there are already compressed so i have excluded them, just add/remove to suit your application.

The payload without compression on my current project is 880kb after compression 620kb, and has shaved a couple of seconds off the browser load time too.

All we need now is for someone to code a netbeans plugin that configures this all for us and makes it configurable from a wizard maybe, any takers ?

I have also stumbled upon this excellent nb6.1 plug-in for pl/sql editing be sure to check it out if you want to edit pl/sql from within netbeans.

Happy coding....

2 comments:

Jorge De Castro said...

Yep, this is neat -and definitely Lecomte's YUI Compressor is the way forward.
It seems to me this solution can be used on Eclipse and IDEA too.
Cheers

Anonymous said...

Hi! I've been reading your weblog for some time now and finally got the bravery to go ahead and give you a shout out from Huffman Tx! Just wanted to mention keep up the great work!
Review my page Find Out More