JSMIN is a JavaScript minifying library that was founded by Douglas Crockford. Minifying is the act of taking your JavaScript code and stripping out unneeded white space and comments to reduce file size. Douglas Crockford offers a set of packages in common server side languages to accomplish this – whether it be PHP, Python or Java. It’s important to note that there are other JavaScript compression and compiling tools out there, I am just giving an example of one that I use frequently.

I’m going to show you what I’ve done with the PHP package of JSMIN.

If you download the PHP package you’ll see how to use is simple:

<?
require 'jsmin-1.1.1.php';
echo JSMin::minify(file_get_contents('example.js'));
?>

Brilliant! It will output a bunch of ugly code right? Well who cares if it’s ugly, it’s only for production. What I wanted to do with this is have something that takes multiple JavaScript files, minifies them and then outputs it to 1 JavaScript file that’s all tightly bundled. Here’s how to do that.

First, you’ll want to make sure that the jsmin-1.1.1.php class is included. Then write a function to handle the minifying of multiple JavaScript files.

<?
/********************************************
* Handle an array of JavaScript files, minify them and output them into 1 file.
* @param string $final_file The path to the final JavaScript file that will contain all minified contents
* @param array $js_files The array of JavaScript files to minify
* @return string The script tag including the path to the final JavaScript file
*/
function drawMinJS($final_file, $js_files){
 
	$contents = '';
	foreach($js_files as $src){
		// We use a semicolon at the end to safely separate the files
		$contents .= JSMin::minify(file_get_contents($src)) . ';';
	}
	$str = '<script type="text/javascript" src="' . $final_file . '"></script>';
	file_put_contents($final_file, $contents);
 
	return $str;
 
}
?>

Then put the snippet below where ever you would like the script tag to appear. Sometimes people put it in the <head> of the document and sometimes right before the </body>

<?
// Not to worry, this outputs the actual <script> tag
echo drawMinJS(
	'js/finalfile.min.js',
	array(
		'js/global.js',
		'js/thickbox.js',
		'js/twitter.js',
		'js/events.js'
	)
);
?>

Voila! The function will take all those JavaScript files in that array, minify them and put them into finalfile.min.js.
I also recommend reading “The best way to load external JavaScript” by Nicholas C. Zakas if you’re looking for more ways to improve performance.