Compress JavaScript and CSS files

Minimizing / compression of JavaScript and CSS code is often encountered technique used to optimize the loading time by reducing weight of the file. Today we will try to briefly tell about the tools used for this purpose.

Compress JavaScript and CSS code

Recently someone asked me about it, so we have today’s small article.

We can establish the principle, that files with JavaScript and CSS placed in a production application are already compressed. Of course always keep the source version, to modify if necessary.

To accomplish the task, we can use one of the compressors. I recommend YUI Compressor:

Download and unpack:

Run the command line, and we can compress. Attention: as the tool is a .jar file, we need Java environment in our system.

Call the .jar file with parameters input_file.js -o output_file.min.js.

For example (note the version in the name of compressor):

c:\yuicompressor-2.4.8>java -jar yuicompressor-2.4.8.jar gameFramework.js -o gf.min.js –charset utf-8

We get the output file.


To avoid any problems with the encoding, I added the flag charset.

Sample code — source and minified version to download:

CSS files are compressed in the same way.

Compressor recognizes the file type by extension; we can also use the –type flag:

–type js|css
The type of compressor (JavaScript or CSS) is chosen based on the
extension of the input file name (.js or .css) This option is required
if no input file has been specified. Otherwise, this option is only
required if the input file extension is neither ‘js’ nor ‘css’.

Other solutions

Certainly YUI is not the only tool to compress JavaScript and CSS — there is a lot of other tools. The “packer” is a good and popular tool:

There are also on-line tools:

Everyone has their own preferences. The main thing is to complete the task quickly and efficiently.

File versions

Couple words about file versions. If we include .js / .css files to the project (not necessarily compressed), a good trick is appending version to its name. Versions of .js and .css files can be set in application configuration.

For example

– CSS: … href=”my.css?v=123″ …

– JS: … src=”myjs.min.js?v=110 …

This will help to avoid caching of the files by browser, and thus when the user of our application runs the latest version, he will get also the latest version of .js / .css files for sure.


It’s actually everything we need to effectively compress JavaScript and CSS files.

Open-source libraries usually are available both in source and compressed version. In case of our code we can easily do the same. Files will get less weight, and moreover no one will look at our code — at least not so easy.

> java -jar yuicompressor.jar thank_you.js -o thank_you.min.js