Jabberwocky

This site is work in progress ...

Easy javascript inclusion in Rails

November 13th 2008

If, like me, you don't like big cumbersome javascript files, and you'd rather load only the javascript you need right this minute, this little hack might help you.

In application_helper.rb : # local javascript for a certain page; this will only appear if this tag is called

 
      
      def use_local_javascript(local_javascript)
        content_for :local_javascript do
          javascript_include_tag local_javascript
        end
      end
      

Then, in the

<head/>
      

in your layout, you put the following:

<%=yield :local_javascript %>
      

Instead of multiplying layouts, you just call the helper on top of your pages, say:

<% use_local_javascript("just_magic.js") %>
      

(needless to say 'just_magic.js' should exist in /public/javascripts/

It's not nuclear science, but it allows you to split your javascript into small manageable bits, and include it only when you need, without multiplying layouts.

Update: in the meantime, there's :javascripts and :stylesheets defined for you by rails, so this code is no longer needed - but a different variant allows you to put actual scripts in the head, like when you want to define a variable.

blog comments powered by Disqus