When writing javascript for a specific page in a site, when do you want to turn the javascript into a function and include it in application.js
?
I've seen suggestions about doing this (and minifying or gzip-ing) to minimize HTTP requests. That makes sense, but what about maintainability? If I have js code specific to one view, it seems like more work to look into a potentially massive application.js
. That code could be embedded into that view or put in its own .js
(or .js.erb
or .rjs
) file in that view folder.
I've seen another suggestion that Rails automatically merges all javascript into one file. Is this true?
TLDR: how much or how little should a developer worry about optimization when writing javascript?
Put javascript functions into separate files, group them logically. My test app indicated that subfolders within .../assets/javascripts/ are ok if and only if the subfolder path is included in the manifest.
As I haven't seen an answer in about a month, I'll answer this question to the best of my current knowledge.
Rails 3.1 (currently at release candidate 4) introduces sprockets, which will compile all javascript in a rails project into one file. It even comes with tools to minify and compress javascript so that it's all delivered to the client at once.
Related to sprockets is the Rails 3.1 asset pipeline. As I understand, it's a folder hierarchy/abstraction. Javascripts can go into 3 folders:
/apps/assets/javscripts/
Javascript files specific to the application, including application.js
. This should only contain the manifest of javascript files you want to include in your project. The rails new
tool will generate this file and include jquery in the manifest.
/lib/assets/javascripts/
Javascript files written by the developer that are more general purpose. (My impression is that this would be for javascript libraries you develop to drop into multiple applications)
/vendor/assets/javascripts/
Third party javascript files (i.e. JQuery, Modernizr)
All files in these folders will appear to the client inside /assets/
, abstracting out the server side file paths. I assume this is meant to help the developer organize javascript files.
To answer my own question
.../assets/javascripts/
are ok if and only if the subfolder path is included in the manifest. //= subfolder/js_file
in the manifest will work. Putting //= js_file
will not if js_file
is inside .../javascripts/subfolder/
/lib/assets/javascripts/
over time. (The goal is to eventually recognize when you want to write general purpose javascript functions as opposed to application-specific ones and eliminate this refactor step)a blog post covering all changes in Rails 3.1
DHH's talk on Rails 3.1 changes, May 16 2011 (~1 hr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With