Javascript Include Tag Best Practice in a Rails Application

后端 未结 4 2215
死守一世寂寞
死守一世寂寞 2020-12-12 11:50

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


<%= javascript_incl         


        
相关标签:
4条回答
  • 2020-12-12 12:28

    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

    0 讨论(0)
  • 2020-12-12 12:37

    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 -%>
    
    0 讨论(0)
  • 2020-12-12 12:43

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

    0 讨论(0)
  • 2020-12-12 12:48

    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 -%>
    
    0 讨论(0)
提交回复
热议问题