Site Navigation
Compressing your javascript
written by vegu on 01 Feb, 2007 04:22:23
Commenting your code and having good, readable formating goes a long way. That's true for javascript as well as it is true for any other programming / scripting language.
However when it comes to javascript or any other script that needs to be downloaded by the user you will want a version of your code that has it's comments removed and takes a up as little space as possible in order to decrease data transfer.
If you have access to a linux box you can do this fairly easily with a command line script and perl.
file_orig="$1"
file_new="$2"
echo "Compressing File: $file_orig TO $file_new"
file_tmp="$file_new.tmp"
cp $file_orig $file_tmp
perl -pi -e "s/^\/\/.*$//g" $file_tmp
perl -pi -e "s/\t/ /g" $file_tmp
perl -pi -e "s/\n/ /g" $file_tmp
perl -pi -e "s/\/\*[^*]*\*+([^\/*][^*]*\*+)*\///g" $file_tmp
perl -pi -e "s/ {2,}/ /g" $file_tmp
perl -pi -e "s/ ?([\=\+\-\*\/]) ?/\$1/g" $file_tmp
perl -pi -e "s/([\}\)\]\;\{\(\[]) /\$1/g" $file_tmp
cat $file_tmp > $file_new
rm $file_tmp
Simply put this code in a shell script and execute it with the first argument being the original uncompressed file and second argument being the name of the file that will be created and hold the compressed code.
./compress.sh script.js script_compressed.js
But what if i have only access to windows?
There are a couple of javascript scrambles out there for windows. They not only compress the code by removing comments and unnecessary spaces and line-breaks but also scramble variables to take the least space possible. That also has the benefit of making your code unreadable and somewhat prevents other people from ripping it off.
However most of those applications cost and i have yet to find one that is freeware.
If you dont care about the scrambling and find that simply removing comments and getting rid of spaces is sufficient then you can use
JSMin. JSMin was created by Douglas Crockford and is a MSDOS executable that essentially does (and some more) what the linux command line script above does.
Related Posts
Your Comment
Comments
No comments yet.