Javascript Include Tag Best Practice in a Rails Application

JavascriptRuby on-RailsHeaderRjs

Javascript Problem Overview


Say I need to call a javascript file in the <head> of an ERb template. My instinct is to do the usual:

<head>
<%= javascript_include_tag :defaults %> <!-- For example -->
</head>

in my application's layout. The problem of course becoming that these javascript files are loaded into every page in my application, regardless of whether or not they are needed for the page being viewed.

So what I'm wondering is if there's a good way of loading a javascript into the the headers of, for example, all ERb templates found only in a specific directory.

Javascript Solutions


Solution 1 - Javascript

I would use content_for.

For instance, specify the place to insert it in the application layout:

<head>
<title>Merry Christmas!</title>
<%= yield(:head) -%>
</head>

And send it there from a view:

<%- content_for(:head) do -%>
<%= javascript_include_tag :defaults -%>
<%- end -%>

Solution 2 - Javascript

I feel there's nothing wrong including all yr defaults since they can then be cached on user's browser.

Solution 3 - Javascript

I would suggest not to add javascript in the header as it causes to load the page slower. Rather load the js at the bottom of the page, which is faster. http://developer.yahoo.com/performance/rules.html#js_bottom

<body>
 ....
  <%= yield(:js) -%>
</body>

And send it there from a view:

<%- content_for(:js) do -%>
  <%= javascript_include_tag :defaults -%>
<%- end -%>

Solution 4 - Javascript

I usually have the following in the layout file:

<head>
  <%= javascript_include_tag :defaults %> <!-- For example -->
  <%= @extra_head_content %>
</head>

And then in the views:

<% (@extra_head_content ||= "") += capture do %>
  <%= other_content %>
<% end %>

See the API documentation for #capture

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbtwView Question on Stackoverflow
Solution 1 - JavascriptmaurycyView Answer on Stackoverflow
Solution 2 - JavascriptJasonOngView Answer on Stackoverflow
Solution 3 - JavascriptJituView Answer on Stackoverflow
Solution 4 - JavascriptGarethView Answer on Stackoverflow