jsmin as a PHP extension – JavaScript Minify the Fast Way
Yahoo’s performance docs and Google’s page speed best practices recommend that both external and inline javascript code is minified. Two popular tools for minifying JavaScript are JSMIN and YUI Compressor.
I needed to have an efficient solution that can minify javascript on the fly. Unfortunately these tools do not work because a process would need to be forked every time minification needed to be performed. In PHP, one possible solution is to use jsmin-php, but again this is a very slow option. jsmin-php is written in PHP code and parsing a JavaScript file in PHP is relatively slow.
So I decided to develop a php extension based on jsmin.c developed by Douglas Crockford. It creates a native PHP function included as a PHP extension (written in C as opposed to PHP). The speed and efficiency improvement over jsmin-php is over 25x!
Try it out!
Get it here
Install instructions (make sure you have development tools installed as well as PHP and its development components):
tar zxf php-jsmin-1.0.tgz
cd php-jsmin-1.0
phpize
sh ./configure
make
make install
(optional) in php.ini add the following line: extensions=jsmin.so
Sample code:
if (!extension_loaded('jsmin')) {
dl('jsmin.so');
}
header('Content-Type: text/javascript');
echo jsmin(file_get_contents('my.js'));
I hope you find it useful.