JSMin is a Javascript source compressor created by Douglas Crockford. The PHP version of this software can be used to compress JavaScript source files 'on-the-fly' - just before serving it. This approach will save your bandwidth without the need for keeping two versions of a script - a compressed one and an uncompressed one. The main disadvantage of this approach is that it is not processor friendly.
There are many other javascript compressors available(including one written by yours truly). Some of the popular ones are given below.
The default method of compression for the JSMin is using a C program but a PHP version(text file) is also given. You can use this to compress your javascript 'live'. If you make an update to the file, you won't have to compress it before uploading it. But this method is processor expensive as some processing must be done to compress the file every time the file is requested.
To use this on your site download the PHP version of JSMin script and rename it to 'jsmin.php'. Then add the following lines at the end of the file - just above the '?>' line.
$js_file = $_GET['file'];
if(file_exists($js_file) and is_readable($js_file)) {
header("content-type:text/javascript");
jsmin($js_file);
}
After the jsmin.php file is configured, you can call any of your javascript script using this HTML
<script src="jsmin.php?file=your_js_file.js" type="text/javascript"></script>
Even though the 'your_js_file.js' file is not in the compressed format, it will be compressed by our script before it reaches the browser - saving your precious bandwidth.
4 Comments:
Hey, great information! I had been looking on the net how to use the jsmin php file... thanks a lot.
Nice tips
there is some typo
link href="jsmin.php?file=your_js_file.js" rel="stylesheet" type="text/css" /
is for linking stylesheet files not javascripts.
@chaoskaizer
Thanks - corrected now.
I know this is an old post, but I thought I provide a little guidance to anyone trying to minify their javascript. I would not use Binny's php example, because it opens up access to other files on your webserver. For example, all a malicious user has to do is browse to one of your scripts, say:
jsmin.php?file=../lib/db.php
And then they will see code that you most likely didn't want them to see.
The way I solve this issue is I built a script that minifies all of the JS files in a given directory, and then puts them in a subdirectory called "compressed". I have an .htaccess file in the js/ folder which rewrites the url to serve up compressed JS from the compressed folder/. I run this minify script whenever I add or edit my javascript files. Using this method, you keep clean, original copies of your code, but you serve up compressed copies. I hope this helps someone with their workflow.
Post a Comment