An easy way to use head.js with Rails 3

26 Dec 2010

While surfing some tech sites the other day, I came across an interesting project called head.js. It’s a simple script that changes the way Javascript is loaded on your site. Instead of listing scripts in the head block, or at the bottom of the page like some suggest, it just loads all scripts dynamically with Ajax requests. This can give your web app a slightly faster load time. This should work well with most web apps, unless you run a lot of custom Javascript calls while the page is loading.

I’ll list the steps to get this working with Rails 3. Other web frameworks will obviously be different.

The first step is to download head.js (I’d recommend just the loading part), and add the following javascript include tag:

<%= javascript_include_tag 'head.load.min' %>

Then add the following function to your application_helper.rb. This was copied from headjs-rails, but I’d rather just add a simple helper method than an entirely new gem.

def headjs_include_tag(*sources)
  keys = []
  content_tag :script, :type => Mime::JS do
    "head.js( #{javascript_include_tag(*sources).scan(/src="([^"]+)"/) { |src|
      key = URI.parse(src).path[%r{[^/]+\z}].gsub(/\.js$/,'').gsub(/\.min$/,'')
      while keys.include?(key) do
        key += '_' + key
      keys << key
      "{ '#{key}': '#{src}' }"
    }.join(', ')} );"