resouce_on_demand plugin

Hi all,

This plugin helps to include javascript and stylesheets only when you need to.

Currently if you want the :defaults javascripts to be included, you include them in the layout and they are called in in all pages that use that layout, even if it’s essentially a javascript static page.

With this you can specify that a layout, or a deeply nested partial requires a particular javascript file, or stylesheet. This will be then included in the head tag of the layout without duplicates. eg you can have a partial iterating over a collection that calls a particular js file every iteration, but only one javascript_include_tag call will be made for that file.

From the README

= resource_on_demand

Allows inclusion of external javascript and stylesheets in the head tag, from anywhere in a view, including nested partials



Looks cool.

I do the same sort of thing fairly extensively with these two helper
methods, which are a bit different:

  # a way of identifying features the layout needs to load
  def require_page_support(*scr)
    @page_scripts ||= {}
    scr.each { |s| @page_scripts[s] = true }

  # used in the layout to query the need for features
  def load_page_support?(*scr)
    @page_scripts ||= {}
    scr.inject(false) {|matches, s| matches || @page_scripts[s] }

Then, in my layout, I have things like this, for example for lightbox:

<% if load_page_support? :lightbox -%>
  <%= javascript_include_tag "lightbox" %>
  <%= stylesheet_link_tag 'lightbox' %>
<% end -%>

The lightbox link helper then just does something like:

  # lightbox support
  def link_to_lightbox(content, action, opts={})
    require_page_support :lightbox
    opts.merge!(:class => 'lbOn')
    link_to(content, action, opts)

If any of this is any use, feel free to pinch it.

Daniel N wrote:

Thanx for the input. Now that I’ve had a sleep on it I’m not sure
that I’m cool with the method names that I used. I think I may
change these to require_javascript instead of demand_javascript.

I’ll have a good look at how your helper methods work when I get home.