Monday, May 20, 2024
18
rated 0 times [  22] [ 4]  / answers: 1 / hits: 50113  / 16 Years ago, mon, march 2, 2009, 12:00:00

As per 'unobtrusive JavaScript' recommendations I want to separate my JavaScript logic into

separate files. However I don't know how to organize them.



Should I:




  1. Just throw all application javascript into Application.js file and load it with layout page? This is simple approach but I will end up with a bloated Application.js. Some users might want to visit only a couple of pages, but this entire file would preloaded which is not good.

  2. Or should I create a separate javaScript file for each view and load them independently? This creates a set of questions. How to link each js file to corresponding view?

    Thanks.


More From » ruby-on-rails

 Answers
26

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.


[#99904] Wednesday, February 25, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminkyrap

Total Points: 631
Total Questions: 89
Total Answers: 109

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;