views:

34

answers:

1

A lot of time, in a partial, the HTML (or ERB or HAML) as well as the Javascript is in one file, so when the main file includes these partials, the HTML will be intermixed with Javascript code.

However, it is said that for fast page content display, all Javascropt code should be placed at the end of the HTML file. In this case, is there a proper or standard way to make this happen? Perhaps using 1 partial as HTML, and 1 partial as Javascript, and include 2 different partials (the HTML as the correct place, and the Javascript near the end of the file?)

(This is related to http://stackoverflow.com/questions/3294885/if-javascript-code-block-is-not-at-end-of-html-file-but-is-using-jquerys-docu )

+1  A: 

In your layout file you could put a footer into which you can load your Javascript (typically stuff like analytics that don't need to be loaded early). Then define a content_for in your views which includes your Javascript partial. The result is that that Javascript will be placed at the end of the page.

In the layout:

<div id="footer">
  <%= yield :footer %>
</div>

In your views/paritals:

<% content_for :footer %>
  <script type="text/javascript">
     // Some Javascript
  </script>
<% end %>

or

<% content_for :footer %>
  <%= render :partial => "path_to_some_javascript" %>
<% end %>
bjg