Question

At the moment my application.js file looks like this:

//= require_tree ./vendor
//= require_directory ./lib

I also have individual JavaScript files for individual views, e.g. home.js, user.js etc.

Do people put these files in the application.js? If so how do they activate them? Most of my JavaScript is executed from the jQuery ready event handler $(function (){ });

Obviously this does not work if they are all in the same file. How could I minify these files and access the correct ready event if they are all in the same file?

Any help or tips greatly appreciated.

Was it helpful?

Solution

It's fine to have multiple jQuery document ready handlers as you shouldn't care about the order between them. You'll need to check that the elements they work on exist before trying to attach any handlers, though.

For example, in home.js, you might have something like

if ($("#home_div").length) { // do some stuff on the home page } 

Doing this is better than splitting up your JS and only serving some pieces on some pages, since with the compiled approach your users only have to download JS once. I think the default rails 3.1 config should minify and concatenate all of your JS in production but not in dev. If you want to enable it manually,

config.assets.compress = true # compress js into one file
config.assets.js_compressor = :uglifier # minify the JS (need the uglifier gem)  
config.assets.digest = true # append hashes to filenames so you can set far-expiry headers for caching

some more info, check out the "customizing the pipeline section" of the docs http://guides.rubyonrails.org/asset_pipeline.html#customizing-the-pipeline

and this related question

How to properly work with jQuery in Rails 3.1 asset pipeline?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top