JQuery and Rails 3

I introduce jQuery to a rails3 application and ask a question about best practices.

It is very useful for me to do all my Javascript unobtrusively using jQuery, but I put everything in application.js. Javascript is included in all my pages since application.html.erb has <%= javascript_include_tag :all %> I also use $(document).ready(function(){…} , which will be executed every time I go from one page to another.

Currently my application is small enough and I see no performance issues. But I'm just wondering how to do it right. Is it better to upload only the appropriate scripts and make round trips to the server? or, including all javascript files at one time is better?

One example of the line that I have in $(document).ready(function(){…} :

$("#user_password").attr("autocomplete","off");

On the one hand, it is very convenient to be able to initialize any password field that I have on any page of the application with one line. On the other hand, I can see how $ (document) .ready () can work very fast very fast, which affects the readability of the code. There is likely to be a lot of code in the $ (document) .ready () code that is not relevant to the current page (for example, the above example on a page that does not contain a password field), does this affect performance?

+4
source share
1 answer

I tried several ways to use jQuery in rails applications, and I came across the simplest, clearest, and most organized way to integrate JavaScript code using *.js.erb files for viewing.

The idea is that you write your user interface behavior in these files (which makes sense since they are part of the View structure in MVC), and then you invoke them if necessary using this:

 $.get(url_for_your_js_view, data, null, "script"); 

You can see this practice in action (and better explained) in this RailsCast .

By the way, it also makes it easy to gracefully fall into a no-script, so I really recommend you take the time to learn this skill, even if it might be a little unintuitive at the beginning.

+2
source

All Articles