StringSmash - Compress JS Strings

By Josh Wright on April 2013 in ideas

 

Sometimes you need to embed really long strings in JavaScript. Ok, rarely. But say you embed some css in JavaScript and the strings repeat a lot. What if you could use JavaScript variables to reduce the repetition? You could save KB in downloads.

This is a quick proof of concept. My goal was to keep it around 50 LOC, so minus comments I did fair. The trickiest part is figuring out which blocks to replace.

View the Source on GitHub

Or use it from NPM with: npm install stringsmash

Before:

var css = 'superlongword superlongword superlongword superlongword superlongword superlongword superlongword';

End Result:

var css = (function(){var a='superlongword';return [a,' ',a,' ',a,' ',a,' ',a,' ',a,' ',a].join('');})();

Whoo hoo! We saved 5 characters! OK not much compression, but longer strings yield better results.

I'm actually doing this for another project which is embedding CSS. My end result was 78% the size of the original, saving about 800 bytes. The whole lib is about 4,800 bytes so it's actually worth it.

It'd be cool if JavaScript minifiers adopted this concept.

Usage:

var css = 'superlongword superlongword superlongword superlongword superlongword superlongword superlongword';
var result = smashjs(css);

console.log(result);       // logs: (function(){var a='superlongword...
console.log(eval(result)); // logs: superlongword superlongword supe...

Here's The Source