4
Sep

[RAILS] Javascript inclusion

posted by gchatz No comments

YSlow says I should move my scripts to the bottom.
It sounds somewhat reasonable since no DOM manipulations can take place, unless the DOM is fully loaded.

Moving the scripts to the bottom will allow the user to see most of the page without waiting for that 400kb of javascript to load. But…
In Rails applications it’s very common to have something like

<%= text_field_for_autocomplete .... %>

This will not work if the above code is before javascript inclusions.
(other than that it will mess up with the html code, prototype helpers are convenient but mess things up badly).

One solution is to use content_for in the application layout.

<script src="/javascripts/myscripts.js" type="text/javascript"></script>

<%= yield :js %>

Now , in your views you can use

<% content_for :js do %> <!-- javascript code to run, for this view only --> <% end %>

And YSlow will stop complaining :)