Javascript Include Tag Best Practice in a Rails Application

﹥>﹥吖頭↗ 提交于 2019-11-28 15:20:49
maurycy

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 -%>

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

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 -%>

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!