jsstrip is a open-source command-line program/module/library to remove whitespace and comments from a javascript file. You might want to do this to optimize size and performance, or to make a file harder to read. It typically makes 30-40% savings in file size (even when compressed by the server).
Using sha1.js (version 2.1a) as a sample, the stripped version is about 35% smaller. Your mileage may vary.
| Original Size | Stripped Size | Savings | |
| uncompressed | 5752 | 3228 | 44% |
| compressed | 2233 | 1437 | 36% |
(in most cases, the browser/server connection will compress the javascript file).
*WARNING*
jsstrip is not a true javascript parser. It assumes you have properly delimited the 'end of line' using a ';' (semicolon).
Yes
print 'foo'; print 'bar';
NO
print 'foo' print 'bar'
You'll have to convert your code to use ';' first.
ALWAYS test the stripped version before deploying to production.
Download
jsstrip comes in two flavors: perl and python. They are mostly identical. They are each self-contained as a single file.
At the moment there is no tarball to download all the secondary files. To get everything, you'll have to use SVN -- see the 'Source' tab above.
Usage
See UsagePerl or UsagePython
Unit tests
Both the perl and python versions have a common set of unit tests. You can run all of them with make test, or each separately with make test-python, make test-perl
News
25-March-2007: both version support MSIE conditional comments now
02-March-2007: reworked parser to handle more cases, all known bugs fixed, added unit tests
Why
I really needed to squeeze the fat out of a comment-heavy javascript file. You'd think that dozens of free utilities would be out there. Maybe so, but what I found was (pick any three):
- Closed source
- Windows only, ActiveX
- GUI-only in Java (why lord why!)
- Written in C (fine but harder to modify)
- Cost money
- Doesn't work
- Requires registration before I can see it
- Written in javascript (yes a JS program to remove white space from javascript)
This doesn't even include the 'Javascript Obfuscators' that attempt to rewrite variable and function names so you can't figure out what is going on. Those were equally crappy.
Random Notes
There is a php version at http://dev.splitbrain.org/reference/dokuwiki/lib/exe/js.php.source.html#1224
the author is andi at splitbrain dot org