wordbotch.com

Blog


Compression of javascript and css

These days I mostly try to minify my javascript and css files. Not really sure why, it's not like there's going to be any noticeable improvement in speed, but every little bit counts.

Before the recent host change, I had been running yui-compressor as a jar:

java -jar yuicompressor-2.4.8.jar -v my.css -o my.min.css

Now I use a combination of uglifyjs and uglifycss. Both are available from bower dependency management.

Included in the bash scripts I run on server setup and update is a call to a python script that goes through and minifies all my *.css and *.js files. Bit hacky, but hey it works.

#!/bin/python

import os

def compress(d, cmd):
    for f in os.listdir(d):
        if os.path.isdir(d + os.sep + f):
            compress(d + os.sep + f, cmd)

        if f.endswith('.js') and not f.endswith('.min.js'):
            fin = d + os.sep + f
            fout = d + os.sep + os.path.splitext(f)[0] + '.min.js'

            print fin, ' => ', fout
            os.system(cmd.format(fin, fout))

        if f.endswith('.css') and not f.endswith('.min.css'):
            fin = d + os.sep + f
            fout = d + os.sep + os.path.splitext(f)[0] + '.min.css'

            print fin, ' => ', fout
            os.system(cmd.format(fin, fout))


d = '../public/assets/css'
cmd = "../node_modules/uglifycss/uglifycss {0} > {1}"

compress(d, cmd)

d = '../public/assets/js'
cmd = '../node_modules/uglify-js/bin/uglifyjs {0} > {1}'

compress(d, cmd)

Then, in my CodeIgniter PHP config, I have some constants defined based on the environment:

if (ENVIRONMENT === ENV_DEV) {
    define('CSX', 'css');
    define('JSX', 'js');
} else {
    define('CSX', 'min.css');
    define('JSX', 'min.js');
}

Then, I include css and javascript files like this:

<link rel="stylesheet" href="/assets/css/somefile.<?=CSX?>"/>
<script type="text/javascript" src="/assets/js/somefile.<?=JSX?>"></script>

This way, I can debug the normal javascript file in development, but it's minified automatically when I deploy it to the server. Usually for external libraries I just always include the minified version, but the same thing would work.