Minify JavaScript Using PHP

Making JavaScript codes is difficult and long. In Web projects, we try our maximum to minify JavaScript and CSS to serve content better. There are many sites on the Web that helps to compress/minify JS code. There is even a PHP Software to do this. In this post, I’ll tell you how to use the PHP jSqueeze library to minify JavaScript code.

Setting Up

You can get the class code of JSqueeze from here. Paste the code into a file called “min-js.php”. We will include this file to compress our code.

The author of JSqueeze has made it a Composer Package. You can install it by :

composer require patchwork/jsqueeze<br />

Compress Code

The JSqueeze class is under Patchwork namspace. We should first make the object :

use Patchwork\JSqueeze;
$jSqueeze = new JSqueeze();<br />

We will now add the JavaScript code into a variable called “$jsCode” :

$jsCode = "function lop(number){
  alert(number + 2);

Or you can include the POST form data in to the variable :

$jsCode = $_POST["code"];

Now, we ask the class to compress the code by calling the $JSqueeze->squeeze() function and include it in the “$minified” variable :

$minified = $jSqueeze->squeeze($jsCode, true, false);

Now, when you echo the “$minified” variable, you will get the minified code which will be something like this :

;function lop(o){alert(o+2)};lop(2);

As you can see, it’s shorter than the original code. This is how compression works. It changed the variables used to shorter ones and used less semi colons.