Integrating YUI Compressor to your Maven Web Project

Size of the javascript files and css files in a website has a big affect on its performance. Especially in slow connections lot of time will be spent on downloading those files. We recently came across such situation. Our website was using jQuery and some other javascipt libraries. Some of them were more than 100kb. Sometimes it took more than 10 seconds to load a page. When we view the loading statistics using developer-tools in Chrome it showed that browser had downloaded more than 500kb of scripts and css.

One way to reduce this script size is to compress them. Our script files contained lot of comments, licencing statements, nice formattings, long meaningful variable names etc... which increases the file size. YUI Compressor is a free utility by Yahoo which can be use to compress our scripts by removing above mentioned things. It is jar file and you can use that and compress file by file.

But that is not very practicle to keep those minimized scripts in develepment since after minimizing you won't be able read them and edit them when needed. Best method is to do the minization when you create the war file. Luckly there is a maven plugin for this. Following is the plugin component you can add to your maven pom.


<plugins>
....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webResources>
<resource>
<directory>
${project.build.directory}/minimized
</directory>
<targetPath>/</targetPath>
<filtering>false</filtering>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>net.sf.alchim</groupId>
<artifactId>yuicompressor-maven-plugin</artifactId>
<version>0.7.1</version>
<executions>
<execution>
<goals>
<goal>compress</goal>
</goals>
</execution>
</executions>
<configuration>
<webappDirectory>
${project.build.directory}/minimized
</webappDirectory>
<nosuffix>true</nosuffix>
</configuration>
</plugin>
....
</plugins>



When you run mnv clean package YUI compressor will compress the scripts and put them in target/minimized folder and those will be used to create the war file.