Javascript includes a Best Practice tag in a Rails app

Let's 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 layout. The problem, of course, is that these javascript files are uploaded to every page of my application, regardless of whether they are needed or not for the page being viewed.

So I'm wondering if there is a good way to load javascript into headers, for example, all ERb templates found only in a specific directory.

+60
javascript ruby-on-rails header rjs
Dec 23 '08 at 21:48
source share
4 answers

I would use content_for .

For example, specify a place to insert it into the application layout:

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

And send it from view:

 <%- content_for(:head) do -%> <%= javascript_include_tag :defaults -%> <%- end -%> 
+110
Dec 23 '08 at 22:02
source share

I feel that there is nothing wrong, including all the default values โ€‹โ€‹of yr, since they can be cached in the user's browser.

+6
Dec 24 '08 at 14:51
source share

I would advise against adding javascript to the header, as it causes the page to load more slowly. Rather load 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 from view:

 <%- content_for(:js) do -%> <%= javascript_include_tag :defaults -%> <%- end -%> 
+3
Jun 19 '13 at 5:51 on
source share

I usually have the following in a 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 API documentation for # capture

+1
Dec 23 '08 at 21:56
source share



All Articles