Javascript organization strategies for Rails 3
I'm currently working on an application with a lot of javascript code. I'm writing inline javascript code on every of the pages/partials, however most of the code is re-utilized somewhere else. I'm trying to figure a way to refactor these little scripts into something more convenient and maintainable. I'm using jQuery, so I'm not using any of the built-in JS generators.
So far I've thought of the following:
Just move everything into
application.js
and take benefit from the new UJS style helpers. This is only a little better than what I have right now because I will end up with a big clunky JS file.Use js_erb gem which provides a way to write javascript source code into
app/javascripts
and get i18n, HTML templates and compilation automa开发者_C百科tically.Use sprockets-rails which also seems a good alternative even I have never tried it and I'm not sure if it's rails3 compatible.
Do you have any experience/suggestion in such topic?
Sprockets 2.0 is under very active development right now and will ship with Rails 3.1 as part of ActionPack. Easiest thing to do is either wait for Rails 3.1 or upgrade to newest Rails 3.1.0.rc4 by pointing your Gemfile at it like:
gem 'rails', :git => 'git://github.com/rails/rails.git', :tag => 'v3.1.0.rc4'
and do
bundle install
In the meantime, get the head start now on how it works:
- http://jackdempsey.me/2011/04/22/rails-3-1-sprockets-and-coffeescript.html
- http://rule52.com/2011/06/sass-and-sprockets-for-rails-31/
Personally I group javascript code into files that make sense and then include them on the pages that require it. For example, if you have some code that is called on most of the pages then I would include it in the application.js. But, if I have code that is only included on my User controller pages then I would make a user.js file and only include it on those pages. By doing this the code is organized in a way that is easy for me to maintain. There might be some performance tradeoffs for this but in my case maintainability is more important.
I group JS code in files, separate from partials
- Partials can be cached and JS updates would not require html cache deletion
- Better code organization, as the functionality gets complicated, it would be easier to manage and optimize
- Over time JS will grow in size and you can use CDN to deliver your JS, this is a great performance booster for page load times
精彩评论