JavaScript file per view in Rails

Load the main JavaScript in application.js every time. Now create files for different needs. Create a form.js file, a myfancypart.js file etc. Don’t load them in the application.html.erb layout. Load them dynamically when you need them:

application.html.erb:

<%= javascript_include_tag "application" %>
<%= yield :javascript_includes %>

top of your view.html.erb:

<% content_for :javascript_includes do %>
  <%= javascript_include_tag "forms.js" %>
<% end %>

Everything in the content_for block will be loaded at yield :javascript_includes.

Leave a Comment