JavaScript file per view in Rails

Solution 1:

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.

Solution 2:

I suggest putting it all into one file, which you can then minify and gzip. The client will only have to download it once, as it'll be cached on all subsequent requests.

Another thing that might interest you is sprockets, a javascript dependency manager, which you can install using gem. You can get more information on sprockets from the website (http://getsprockets.org/) or from the github page (https://github.com/rails/sprockets). It makes writing big javascript applications much more manageable.

Solution 3:

This changes with Rails 3.1 and the asset pipeline!!!

Separate files are best as you indicate. The issues about how to reference them all and link them goes away with rails 3.1 which aims to compile them all into single files for production.

Solution 4:

One can use Jammit to include css and javascripts files

for detail: http://documentcloud.github.com/jammit/

Use:

step 1:

Add js-files in assets.yml (see code below)

javascripts:

footer:

- app/javascripts/lib/*.js
- app/javascripts/jquery-plugins/*.js
- app/javascripts/custom/*.js
- app/javascripts/application.js

header:

- app/javascripts/core/*.js
- app/javascripts/head/*.js

step 2:

Add simple code in application layout:

<%= include_javascripts :header %>
<%= include_javascripts :footer %>