I had some time today to re-visit some of the javascript on TaxiMe. I know it uses a lot of it. So here are some key things I’ve done to help bring down the load time:

  • Use a javascript minifier: Since I load in about 4 javascript files I figured i should probably serve them up as small as possible. I went out digging and found a PHP javascript minifier at http://code.google.com/p/jsmin-php/. I modified it slightly to take multiple files and pack them into 1 instead of making 4 different requests. It brought the 4 request totaling 51.99 KB to 1 request totaling 37.3 KB. Some people might wonder why I chose a minifier instead of a packer. Although the packer compacts it into a smaller file size, it actually makes your browser work harder to decompress it. A packed file is also way harder to debug than a minified file. This is also why the new jQuery 1.3.1 does not offer a packed version for download.
  • Take advantage of Google’s Ajax Library API: Some people may not know this but Google offers to various versions of javascript libraries. These libraries include jQuery, Prototype, Mootools and a few others. All you have to do is include the path http://www.google.com/jsapi in the src of your script tag. You can then call “google.load(‘jquery’,’1.3.1′)”. There are a few advantages to this: One being that Google hosts all versions so it makes it easy to swap back and forth. Another is that it uses CDN which stands for “Content Delivery Network”. This means that when a user visits your site and has to download jQuery, Google will look for the closest server to that user, making the download a lot faster than downloading it from your server (which could be lightyears away). My favorite is the caching that it does. If a user visits multiple sites linking to jQuery that is NOT hosted by Google it will cache it even if it’s the same file – so you could have multiple copies of a jquery.js file stored in your cache. With it being hosted by Google, it recognizes it and will not attempt to download the same file twice.
  • Cache elements: One of the last things I did was go into all my javascript files and look for multiple instances of $(‘#myelement’).someMethod(). When you call this you have to remember that you’re calling document.getElementByid(‘myelement’) each time. Why don’t you just call it once and store it? Something on initialization like “this.myelement = $(‘myelement’);” Then when you need to call a method on it, just do this.myelement.someMethod(). If you only have a few instances like this, it probably won’t make a noticeable difference but when you have many instances you will notice a change.

All in all, my optimization was successful. TaxiMe’s load time was 4.5 seconds and I brought it down to around 3.5. Was this all worth 1 second of load time? Yes. It was.