New Rails plugin: DistributedAssets

I’ve followed the discussions on speeding up page load times over at Ezra’s Blog, where he’s been showing code that generates image URLs that will essentially distribute asset requests over multiple hosts.

The theory behind this technique is that web browsers tend to not make more than 2 concurrent requests to any given hostname. Now, if your page has lots and lots of assets (javascript includes, linked stylesheets, images, and so forth) page download times will decrease when you’re able to fool the browser into thinking it’s talking to multiple hosts (which, again, get 2 concurrent requests each), while it is in fact only talking to a single host. (Actually, nothing prevents you from using multiple machines, either.)

In Ezra’s post, he added a new view helper to generate asset URLs, which could then be fed to image_tag and friends. He also mentioned this could well be made into a more universal plugin, which doesn’t require any changes to your application code. Well, tadah, here it is.

Install:

# script/plugin install svn://poocs.net/plugins/trunk/distributed_assets

Configuration is simple. Instead of configuring a single hostname, like so:

# config/environments/production.rb
config.action_controller.asset_host = "http://assets.domain.com"

you set asset_host to an array of hostnames, like so:

# config/environments/production.rb
config.action_controller.asset_host = %w(
  http://assets1.domain.com
  http://assets2.domain.com
  http://assets3.domain.com
  http://assets4.domain.com
)

Boom, done. From that point on, any URL generated from Rails’ asset tag helpers (such as image_tag, javascript_include_tag, and stylesheet_link_tag) will end up being served from one of your defined hosts. To be more specific, each asset will be served from the same host every time to not interfere with browsers’ caching.

Thanks to Ezra for coming up with the original idea (and code).

Filed Under: Rails