Home > General, PHP > jsmin as a PHP extension – JavaScript Minify the Fast Way

jsmin as a PHP extension – JavaScript Minify the Fast Way

June 11th, 2009

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.

igor General, PHP ,

  1. July 2nd, 2009 at 09:55 | #1

    Thanks Eric and Igor, you guys are my hero! This is much better than jsmin-php. Your install instructions worked perfectly under Gentoo Linux without any tweaks.

    You have inspired me too create a small PHP script to quickly minify javascript files on the commandline:

    #!/usr/bin/php
    <?php
    /**
     * jsmin for the commandline
     *
     * Feel free to use and distribute as you wish.
     * Don't blame me for any damage this script might produce
     */
    $instructions = "Usage: jsmin SOURCE [TARGET]
    Remove comments and unnecessary whitespace from JavaScript files.
    Example: jsmin test.js test.min.js";
    try {
       if (empty($argv[1])) {
           throw new Exception('Missing SOURCE argument!');
       }
       if (empty($argv[2])) {
           // no TARGET file specified, minify to STDOUT
           fwrite(STDOUT, trim(jsmin(file_get_contents($argv[1]))));
       }
       else if (!file_exists($argv[2])) {
           // TARGET file does not exist, minify to new file
           jsminPutContents();
       }
       else {
           // TARGET file exists, ask to overwrite existing file
           fwrite(STDOUT, "Overwrite '{$argv[2]}'? [Y/N]: ");
           if (strtoupper(trim(fgets(STDIN))) === 'Y') {
               jsminPutContents();
           }
           else {
               exit(fwrite(STDOUT, "user aborted!\n"));
           }
       }
    }
    catch (Exception $e) {
       fwrite(STDOUT, 'ERROR: ' . $e->getMessage() .
          "\n{$instructions}\n");
    }
    function jsminPutContents() {
       global $argv;
       file_put_contents($argv[2],
          trim(jsmin(file_get_contents($argv[1]))));
       fwrite(STDOUT, "done!\n");
    }
    // EOF
    

    This code presumes that you are running PHP5, that PHP-CLI is located at /usr/bin/php, that the above script is named ‘jsmin’ and is executable and resides in your system PATH. The only thing I noticed is that jsmin outputs content with leading newlines, that is why I have wrapped the output with a trim(). Feel free to use this script at your own risk (of overwriting existing files) in any way you wish.

  2. smcnally
    July 16th, 2009 at 14:57 | #2

    thanks for this module, Igor.

    I’m wondering where I need to run make / make install from:

    I’m on Ubuntu 9.04 and have got apache modules here:

    /usr/lib/apache2/modules

    and php modules here:

    /usr/lib/php5/20060613/

  3. July 16th, 2009 at 15:05 | #3

    From the directory that was created when you untared the file. You should be able to issue each one of those commands exactly as shown in that order.

  4. smcnally
    July 16th, 2009 at 16:08 | #4

    thanks – I untarred the file in my home dir.

    should i untar it from elsewhere?

    (i am not seeing jsmin as a module in phpinfo after an apache restart, so I’m presuming untarring / make / make install from my home dir didn’t place the req’d files in the correct place[s])

  5. smcnally
    July 16th, 2009 at 17:33 | #5

    update: i didn’t have php5-cli installed. I installed that, re-ran through Igor’s instructions above and ran a test. It’s working.

    The output from make was less-than clear to me w/r/t where the libs we’re being placed. I had to run make install as su. (apologies if these are Duh!, but …)

    there’s still no sign of jsmin in phpinfo, so I ran a test to confirm i can minify. Confirmed.

    Very much looking forward to using this. Many thanks

  6. July 23rd, 2009 at 18:32 | #6

    I would recommend wrapping this in a function so you can include some caching. This will help you run minify only once an hour, max.

    function minify($file)
    {
    $cache = ‘cache-’.$file;

    if(!file_exists($cache) || filemtime($cache) > 3600)
    {
    $content = jsmin(file_get_contents($file));
    file_put_contents($cache, $content);
    }

    return file_get_contents($cache);
    }

    Usage:

    if (!extension_loaded(’jsmin’))
    {
    dl(’jsmin.so’);
    }
    header(’Content-Type: text/javascript’);

    echo minify(’my.js’);

  7. July 23rd, 2009 at 18:43 | #7

    @smcnally
    The extension gets installed to wherever your PHP extensions are kept. It varies for every installation. If you want to load jsmin in apache automatically, you need to edit your php.ini file and add the extension line.

  8. September 8th, 2009 at 19:20 | #8

    JSMin by default strips conditional compilation. This can be avoided by a simple patch (but this modification isn’t spreaded through the web). Web Optimizer ( http://code.google.com/p/web-optimizator/ ) has JSMin included (among YUI Compressor and Packer) and can help in automation of minify and merging you client side logic.

  1. June 23rd, 2009 at 16:21 | #1