Combine and minify Javascript files with PHPCombine and minify Javascript files with PHP

Posted July 16th, 2009 in Javascript and PHP

If you're using a Javascript library like jQuery it's likely you'll end up with many Javascript files that need to be included in each page request. Ideally these should be combined into a single file and minified to cut down on page load time. This post shows how to use jsmin-php to combine multiple Javascript files into a single minified file.

jsmin-php

jsmin-php is a fast, low-overhead port of Douglas Crockford's JSMin JavaScript minifier to PHP. It requires PHP 5 or higher. It can be downloaded here at GitHub.

The PHP code

I prefer to run a batch process to combine the files and then let Apache serve a single static file using mod_deflate rather than mess around running PHP on each page request. I keep all the Javascript files to be merged in a directory under the web root at /js/merge and then put the combined output into /js/combined.js . You can change this to whatever suits you.

The code to combine the files looks like this:

require_once('jsmin-1.1.1.php');

$files = glob("/path/to/js/merge/*.js");
$js = "";
foreach($files as $file) {
    $js .= JSMin::minify(file_get_contents($file));
}

file_put_contents("/path/to/js/combined.js", $js);

The code explained

First up we need to require the jsmin library. Substitute the filename for the version you are using, and add any additional paths required before the filename.

require_once('jsmin-1.1.1.php');

Next use glob() to find all the files ending with .js in the directory /path/to/js/merge

$files = glob("/path/to/js/merge/*.js");

Initialise a variable to contain the Javascript:

$js = "";

And now loop through the list of files, adding the minified Javascript to the variable:

foreach($files as $file) {
    $js .= JSMin::minify(file_get_contents($file));
}

Finally, save the combined Javascript to a file at /path/to/js/combined.js:

file_put_contents("/path/to/js/combined.js", $js);

Alternative to glob

Instead of using glob() you could list the files to be merged in an array that you update manually yourself by substituting the $files = glob("/path/to/js/merge/*.js"); line with something like this:

$files = array('file1.js', 'file2.js', 'file3.js');

And change the file_get_contents part to this:

file_get_contents("/path/to/$file")

Development vs Production

The way I use this myself is to use the individual files on my development version of a website and the combined version on the production version of the website. That way when I'm developing I don't need to run the batch script every time I make a change to one of the Javascript files.

Related posts:

Comments

blog comments powered by Disqus