Minimizing Javascript and CSS in Eclipse

Websites need to load as quickly as possible. The results of Internet connections being faster and faster is that we can’t stand anymore waiting for a page to load. We’re used to speed and if the page doesn’t load, I’ll just close the tab and go somewhere else.

Minimizing is the process of reducing the size of CSS and JavaScript files by compressing it. This is achieved by removing unnecessary white spaces and newlines and also by renaming JavaScript variables to something shorter. With this technique I’ve managed to reduce the size of some JS files by 50%. Yahoo! provides a wonderful tool called YUICompressor that does the job for you.

I’ve been looking for a way to automatically minimize JS and CSS files upon save in Eclipse in my PHP projects… finally found out how to do it!

The idea is to edit .src.js and .src.css files. When saving the file, Eclipse will minimize it and create or update the corresponding .js or .css file using YUICompressor. So you will be editing the .src.js or .src.css file while of course, your website uses the .js or .css files. Note that I’m using Eclipse PDT.

We simply need a shell script (Mac OS or Linux) or Batch script (Windows) that minifies the file. Here’s the Mac OS / Linux shell script:

#!/bin/bash
# minifies js and css files
# by Nicolas DEBARNOT
if [ -f $1 ]
then
 file=`echo $1 | sed 's/\.src//'`
 java -jar yuicompressor-2.4.2.jar $1 -o $file --charset utf-8 --nomunge
fi

And the Windows batch script:

@echo off
set inputfile=%1
set outputfile=%inputfile:.src=%
java -jar yuicompressor-2.4.2.jar %inputfile% -o %outputfile% --charset utf-8 --nomunge

In Eclipse, open project properties, add a new builder, put under “location” the path to the minimizer script. Working directory should contain the yuucompressor-2.4.2.jar file and give it as argument the current resource using Eclipse’s variables: ${resource_loc}.

Make sure that “The selected resource” is checked in the “Refresh tab” and that “During auto builds” is checked in the “Build Options” tab.

Save your new builder and make sure that “Build Automatically” is checked in the “Project” menu and voilĂ !

  • Share/Bookmark

Tags: , , , ,

Leave a Reply