简体   繁体   中英

Combining many JS files with Rails Asset Pipeline

I am making a long-overdue upgrade from Rails 3.0.20 to Rails 3.1.10. (Later I'll upgrade to 3.2, but I want to get the more major changes in 3.1 working with my codebase first. I don't have a test suite, so please bear with me as I overcome quite a bit of technical debt. Thankfully, the app isn't that large or complex.)

I've always had separate JS files for the various views in my app. Now, Asset Pipeline wants to combine all of those into one file. Problem is, a lot of my variables and function names collide and generally just cause problems.

My assumption is that I need to use some kind of namespacing here, and then initialize the code in a particular namespace on the page that needs it.

Is there a standard way to do this? Or, is there a better way overall?

One note of clarification: I'm not ready to switch to CoffeeScript yet.

The keystone of the asset pipeline is the manifest file. By default Rails creates one for JavaScript files at

app/assets/javascripts/application.js

This manifest uses directives to declare dependencies in asset source files. One of these directives is

require_tree

which works like require directory, but operates recursively requiring all files in all subdirectories. In my Rails application the generated application.js contained

//= require_tree .

Which requires all files inside the JavaScript asset folder. By removing it, not all your JavaScript files get combined into one anymore. Then you have to require the JavaScript files per view. This is answered in the question JavaScript file per view in Rails .


Having said that, please reconsider your plan. After all Rails does not do this to annoy you, but for a purpose. For reasons of efficiency you should have as few HTTP requests as possible. If all your JavaScript code gets loaded upfront you might have better performance, for instance due to caching.

The asset pipeline will allow for separate js files for each view. In app/assets/javascripts you will be able to have a separate js file for each view. So lets say your have models books and magazines. In app/assets/javascripts you can have books.js and magazines.js (or coffee) for each model/view.

Also, if you have not watched http://railscasts.com/episodes/282-upgrading-to-rails-3-1 give it a look/see.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM