Search code examples
phpjavascriptminify

How to minify JS in PHP easily...Or something else


I've done some looking around, but I'm still confused a bit.

I tried Crockford's JSMin, but Win XP can't unzip the executable file for some reason.

What I really want though is a simple and easy-to-use JS minifier that uses PHP to minify JS code--and return the result.

The reason why is because: I have 2 files (for example) that I'm working between: scripts.js and scripts_template.js

scripts_template is normal code that I write out--then I have to minify it and paste the minified script into scripts.js--the one that I actually USE on my website.

I want to eradicate the middle man by simply doing something like this on my page:

<script type="text/javascript" src="scripts.php"></script>

And then for the contents of scripts.php:

<?php include("include.inc"); header("Content-type:text/javascript"); echo(minify_js(file_get_contents("scripts_template.js")));

This way, whenever I update my JS, I don't have to constantly go to a website to minify it and re-paste it into scripts.js--everything is automatically updated.

Yes, I have also tried Crockford's PHP Minifier and I've taken a look at PHP Speedy, but I don't understand PHP classes just yet...Is there anything out there that a monkey could understand, maybe something with RegExp?

How about we make this even simpler?

I just want to remove tab spaces--I still want my code to be readable.

It's not like the script makes my site lag epically, it's just anything is better than nothing.

Tab removal, anyone? And if possible, how about removing completely BLANK lines?


Solution

  • I have used a PHP implementation of JSMin by Douglas Crockford for quite some time. It can be a little risky when concatenating files, as there may be a missing semicolon on the end of a closure.

    It'd be a wise idea to cache the minified output and echo what is cached so long as it's newer than the source file.

    require 'jsmin.php';
    
    if(filemtime('scripts_template.js') < filemtime('scripts_template.min.js')) {
      read_file('scripts_template.min.js');
    } else {
      $output = JSMin::minify(file_get_contents('scripts_template.js'));
      file_put_contents('scripts_template.min.js', $output);
      echo $output;
    }
    

    You could also try JShrink. I haven't ever used it before, since I haven't had difficulty with JSMin before, but this code below should do the trick. I hadn't realized this, but JShrink requires PHP 5.3 and namespaces.

    require 'JShrink/Minifier.php';
    
    if(filemtime('scripts_template.js') < filemtime('scripts_template.min.js')) {
      read_file('scripts_template.min.js');
    } else {
      $output = \JShrink\Minifier::minify(file_get_contents('scripts_template.js'));
      file_put_contents('scripts_template.min.js', $output);
      echo $output;
    }