Minify Javascript using PHP

All those newbie web developers out there might have noticed that javascripts are often written in minified forms. When you try and debug the pages you Google, Facebook etc. It can be noticed that the javascript written there is nowhere close to be understood. This is done deliberately by these tech giants to make it difficult for the developers to decipher their code. Also, it makes the process of fetching the javascript from the server faster.

When there are a number of javascripts to be loaded, the individual calls to the javascripts are combined so that a fewer number of server requests can serve the purpose. All this is done by minification of the javascript. There are several ways to minify a javascript. One of them is a two step process to achieve the awesomeness of Google or Facebook like minified javascripts.

1) Minification :  In this step, all the line breaks, tabs and white spaces are removed and the javascript is converted into a one line code without any sort of formatting to make the server respond faster to any request for the javascript.

2) Obfuscation : In this step, the minified javascript from the above step is obfuscated so as to hide the actual javascript and make it really confusing,ambiguous and harder to interpret for any person.

So here is a quick tutorial to minify it on the fly using PHP so that the original javascript code remains intact.

1) Download the JSMin PHP file from : https://github.com/rgrove/jsmin-php/blob/master/jsmin.php for minification of your javascript.
2) Download the Packer PHP file from : http://joliclic.free.fr/php/javascript-packer/en/ for obfuscation of your javascript. (Just need the JavascriptPacker.php from the complete zip)

Now save these files into your codebase library or any other suitable place and using these two masterpieces, a javascript can be easily minified using the following PHP code.


//Using the two files and including them onto the PHP page (i.e. JSMin and JavascriptPacker).
require_once('jsmin.php');
require_once('jspacker.php');

//Minification using jsmin.php
$js = file_get_contents('my_javascript.js');
$js = JSMin::minify($js);

//Obfuscation using jspacker.php
$myPacker = new JavaScriptPacker($js, 62, true, false);
$js = $myPacker->pack();

//Display the final ouput wherever it is required.

echo $js;

Now, wherever you want your javascript my_javascript.js to be loaded, in the script tag, just add the 'src' attribute to the PHP file where your above code is put up.

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

So easy to get the awesomeness. Get amazed with the minified javascript. Even the person who wrote the javascript won't be able to decipher it from the minified form. Hope this helps some of the web developers !! 

Comments

Popular Posts