Blog.init();


A technical blog on Computer Science and Software Development topics by Tomás Pérez.


Minimizing javascript libraries

The minification of static file bundles is an useful process to improve the performance of the client side of web applications.

This process removes comments, blank spaces, EOL, tabs, etc. from the Javascript code. That way the size of the files downloaded by the browser is reduced, therefore load time is reduced. In addition, as a part of the minification process, and depending on the compiler used, the Javascript execution time can be improved since the code is optimized for the interpreter.

The following is a very basic example of a minification script, using a tool included by the Javascript library YUI (Yahoo User Interface) called the YUI compressor.

http://yuilibrary.com/downloads/#yuicompressor

  • YUI Compressor is a Java tool, therefore we need the Java Runtime Engine to be installed in the system.

  • The minified file will be generated with the same name than the original appending the extension .mymin.js.

  • The Javascript code responsible of loading the javascript dependencies will try to load by default the minified versions, and if they are not present will do a fallback to the original files. That way we can combine a development/production development environment with just a minor changes, where we have the minified files available only in production.

minify.sh
#!/bin/sh

# Filtering pattern
PATTERN=\.js$

# Directory to find the files (recursive).
DIR=$1

list=`find $DIR | egrep $PATTERN`

for i in $list
do
  java -jar yuicompressor-2.4.2.jar $i -o $i.mymin.js
  echo generated $i.mymin.js
done
Usage
sh minify.sh /var/wwwroot/development/libsjs