Saving bandwidth with Rails

You should always want to minimize server bandwidth. This means that you want to send as few files as possible, and those files should be as small as possible.

Scott Becker wrote a nice Rails plugin called AssetPackager to compress and merge your javascript and stylesheet files. It allows you to merge an arbitrary number of .js/.css files into 1 file. You can determine the order of the files. The plugin then removes whitespace and comments from it and performs some other tricks to make it as small as possible.

NOTE: Rails also allows you to merge all the js files by adding :cache => true to javascript_include_tag

Since websites contain a growing number of javascript files these days, this is a big win.

A warning: Don’t include javascript files that are updated and deployed very often. With every new deploy, the one merged javascript file that used to be cached client-side has to be downloaded again.

In the example below, the difference becomes quite clear:

without merging/minifying:
not-minified

with merging/minifying:
minified

As you can see, the size is cut by 70k, but this is not the big win. The fact that it merges all javascript files into one makes sure that requests don’t have to wait for each other (the grey colour of the blocks is the download time, the rest is just queuing and waiting). The total time is reduced from 972ms to 207ms. Now that’s still only 0.77 seconds, but imagine what the gain would be for a larger website:

firebug javascript statistics
See the image above: Although the files are cached, 28 requests for javascript is just a bit too much.

Posted April 21st, 2009 by Martijn Lafeber
 

Comments

 
  1. Wow! this is wonderful.It royally helps in saving bandwidth in turn resulting into more efficient and fast transfer with less traffic.

    Posted April 23rd, 2009 20:59 by Jim
  1. Also check out bundle-fu at http://code.google.com/p/bundle-fu/

    This one doesn’t require you to put your javascript/css references in a seperate file. It parses the “script” and “link” tags you normally output and bundles/minifies them based on that. Just surrond the output with “bundle do … end”

    Posted April 27th, 2009 10:52 by Alex
  1. [...] Innovation Factory Dev Blog ยป Saving bandwidth with Rails [...]

  1. [...] quickly get too many server requests when you have many separate images on one page. This is bad. So I thought of making a sprite of all the world’s flags. I’ve tried spriteme first [...]