开发者

jQuery and Rails 3

开发者 https://www.devze.com 2023-01-14 11:08 出处:网络
I\'m introducing jQuery into 开发者_运维百科a rails3 application, and have a question regarding best practices.

I'm introducing jQuery into 开发者_运维百科a rails3 application, and have a question regarding best practices.

I'm finding it very useful to do all my Javascript unobtrusively using jQuery, but I'm putting everything in application.js. The javascript is included in all my pages, as application.html.erb has <%= javascript_include_tag :all %> I'm also using the $(document).ready(function(){…} which is going to execute every time i go from one page to another.

Currently, my application is small enough that i don't see any performance problems. But, I'm just wondering what is the right way of doing it. Is it better to load only the relevant scripts and have round trips to the server? or, is including all javascript files in one go better?

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

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

On one hand, it is pretty handy to be able to initialize any password field I have on any page of the application with one line. On the other hand, I can see how $(document).ready() can get really long very quickly, affecting code readability. There is also likely to be a lot of code in $(document).ready() that doesn't pertain the current page (e.g. the above example in a page that doesn't have a password field), does this affect performance?


I have tried a few ways of using jQuery in rails apps and I've encountered the easiest, clearer and most organized way of integrating JavaScript code is using *.js.erb view files.

The idea is you write your UI behavior in this files (what makes sense, since they are part of the View in MVC structure) and then you call them when necessary with 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 easy to gracefully fall down to a no-script scenario, so I really recommend you to take the time to learn this skill, even when it may be a little not-intuitive at beginning.

0

精彩评论

暂无评论...
验证码 换一张
取 消