Web Development

Web Development Tips & Tricks, the things that you don’t want to figure out.





Archive for the ‘htaccess

Shrinking Javascript the Better Way

Thursday, February 28th, 2008

Hello everyone!

There are many ways to shrink or obfuscate Javascript, simply search Google and you should find plenty of results. I found that many are programs that shrink it, then you upload the new code, which I was going to use until I found a better solution.

I found two that were recommended, jspacker and JSMin. After searching for jspacker and finding their site down, I went to JSMin. I found links at the bottom for PHP code that would do it on the spot, which made me happy because I figured I could figure out a way to do something tricky with it, which I did.

Through the use of .htaccess, JSMin and another file I created, I made the site I was working on automatically shrink all my Javascript files when called, but look completely normal in Dreamweaver.

Here’s the code:

.htaccess

Options +FollowSymLinks
RewriteEngine on

RewriteRule ^js/(.*).js$ /js/minimize.php?jsPage=$1 [L]

Quick note, I keep all my Javascript files in a folder called “js” which is also where “minimize.php” is located. You can adjust this according to your setup.

includes/minimize.php

<?php
require(‘../includes/jsmin.php‘);

// Output a minified version of the Javascript file.
echo JSMin::minify(file_get_contents($_GET['jsPage'] . ‘.js’));
?>

Again, should adjust the include of the “jsmin.php” which can be downloaded here. Also, with the way I set it up, “minimize.php” must be in the same folder. You can adjust all of this however you like, but this was the best for my use.That’s it! Basically what’s happening is when the site calls your “example.js” file, it instead reads the file “minimize.php?JSPage=example”, which then minimizes and outputs the “example.js”.

-Kerry