December 22, 2010

Dynamic Stylesheet/Javascript Loading in Rails

Sometimes when I'm coding Rails applications, it's useful to split up CSS and Javascript files by controller/views to prevent loading a huge CSS or Javascript file (containing all of the styles and code for the entire application) on every single page of the application when you only really need it for a specific set of your pages.

To load these dynamically (without having to include each named stylesheet by hand on each page), use the following code in the head of the main application layout:

<% filename = controller.controller_name %>
<% if FileTest.exist?  RAILS_ROOT + "/public/stylesheets/" + filename %>
  <%= stylesheet_link_tag "#{filename}" %>
  <%= javascript_include_tag "#{filename}" %>
<% end %>

This assumes that your stylesheets and javascript files are named according to the controller views in which they appear; if you'd just like to include javascript files of your choosing on certain views, put this in the head of the main application layout:

 <%= yield(:header) %>

And insert this code in your view with the appropriate CSS and javascript files you'd like to include:

<% content_for :header do %>
  <%= javascript_include_tag "file.js" %>
  <%= stylesheet_link_tag "file.css" %>
<% end %>