Jabberwocky

Easy javascript inclusion in Rails

Posted in jabbascript, rails by elisehuard on November 13, 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.

Advertisements
Tagged with: ,

One Response

Subscribe to comments with RSS.

  1. amitmondal said, on February 14, 2011 at 8:04 am

    Nice tutorial….thanks for this post…..
    Please visit this link for learn more script.
    http://amitmondal.wordpress.com/


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: