Thursday, August 19, 2010

Javascript optimization for web applications

There are a number ways in which you can go about optimizing your web application. This is one of the places where you could probably find the holy grail.

Javascript download time is one of the major bottlenecks for web applications. Let me explain how i managed to reduce the download time of my incredibly huge and chunked javascript files to reduce load times.


While in development stages, it is nice and developer friendly to modularize javascript into various files and folders, the load time gets really ugly when you put the app into production. Given that most of us various web frameworks/libraries like dojo, jquery, ext-js etc.. which themselves load a number of javascript files in turn depending on their usage, it is better to optimize your javascript.
Combine your javascript


This should be pretty simple. You can start off by writing a simple java class which takes in a list of files as an argument. This would then read all the contents of the files and write them out into a simple file. You could call that "combined.js". You can call this as a task from your build script such as ant

Compress the resultant javascript (minification)

The combination process just produces a huge single bulky file. This will result in reducing the number of HTTP requests for javascript files but you would still have to deal with the size of the javascript file. There are number of tools which allow you to compress your javascript files. The compression basically minifies your code in the sense that all the formatting in the code (spacing/indenting even carriage returns) is removed out and variable names are "optimized". You cannot probably debug using this compressed version of javascript. I have been using YUI compressor in my project with much satisfaction. A number of resources are available on how to perform this and hence i am not going to blog about it here. You can probably find a good article on how to use the yui compressor in your ant task over here

GZip javascript

One of the final steps you could try to do is to gzip the resulting javascript. This really reduces the size of the javascript file that is to be downloaded to the client. I could manage to compress a 500 kb(approx) javascript file to about 90 kb. I will talk about gzip process in my next blog.

Since javascript resources are one of the main bottlenecks in an application loading process (along with heavy images), the above three steps should help you speed up your application load time.

Note that you could also apply above process for your CSS files if they start to become too large or even gzip your html files if they are large enough and take a while to download.

No comments: