Elliot Swan

Welcome to my live redesign. Codename, Tumbl3. Grab the feed.

Wednesday (01/31/07)

One Framework To Rule Them All: Compiling & Compressing Your Favorite JavaScript Libraries 7:28 pm

If you’re anything like many of the JavaScript developers around, you’ve got your own choice libraries, functions, and addons that you like to employ for many of your projects. Sometimes they can get fairly large (especially if something like Script.aculo.us is involved), but luckily, we can reduce that.

For example…

One Library to rule them all, One Library to find them,
One Library to bring them all and in the darkness bind them
In the Land of Web 2.0 where the JavaScripts lie.
– J. R. R. Tolkien

Perhaps you use Prototype, Script.aculo.us’s effects.js, Event:Selectors, and a DomReady function (a few libraries that make my coding so much faster). That’s 4 JavaScript files, amounting to around 113KB…Fairly big. It’s also a pain to always have to include 4 .js files in my <head> all the time.

So why not just have one?

Combine Them

There’s really just no reason to have 4 seperate library files, some only amounting to 2KB–It’s just a waste of space in my <head>, and I’m kinda picky about that sometimes, OK? So first thing’s first, let’s throw them all in one file and name it library.js.

Bam. Suddenly, we have one file which now makes everything look cleaner…but it’s still huge.

Compress Them

There are several options out there, but if we use Dojo ShrinkSafe we can combine both this step and the previous one by compressing several files at once (note: this will compress files together in the order that they are listed, so if some files are dependent on others, make sure they come after the main ones). This will strip out all comments, so in order to comply with license’s make sure to then go back and place them back in at the top.

In my example, this turned my four 113KB files into one 75KB file–which is only 3KB bigger than just Prototype alone, effectively reducing file size by 38KB. Not bad.

By why stop there?

We can also gzip it using mod_gzip or Mike P.’s PHP/.htaccess scripts, which should speed it up even more (just make sure to adjust them for .js files rather than .css files).

In Closing…

Libraries like mootools and YUI are sometimes doing some of this for you, but not all do and sometimes it’s nice to mix-and-match. swan

  • Jake Scott February 2nd, 2007 @ 5:04 pm (#)

    Your site is soo uber it is ridiculous! Good work mate.

  • Elliot Swan February 2nd, 2007 @ 7:01 pm (#)

    Thanks. :)

Say Something.





I'm a nice guy, so I'll let you use basic XHTML such as <a>, <strong>, <em>, <blockquote>, and <code>. If you're trying to share some code with us, just make sure to run it through Postable first.

Write your comment