问题
I use a jQuery plugin that loads another js file from the server after the initial page load. Since all js assets are concatenated in Rails 3.1 and the public directory is not used to serve js assets, how can I reference this file? Where do I put it?
回答1:
Every asset in the Sprockets load path is accessible at runtime. You can see your load path in Rails console with
Rails.application.config.assets.paths
You can add load paths in an initializer:
Rails.application.config.assets.paths << your_load_path
By default, all assets in apps/assets/ and vendor/assets/ are loaded automatically. These assets must be located inside directories. Files in the assets/ directory itself are not loaded.
You can load an asset located at apps/assets/javascripts/myscripts/hello.js
by visiting http://mydomain.com/assets/myscripts/hello.js.
Concatenation is a separate concern. Sprockets will look in the load path for assets that that you specify using the Sprockets require
and provide
directives and build concatenated files from them.
回答2:
There does not appear to be an easy way to accomplish this. Within Rails 3.1, both JavaScript and CSS files are now concatenated into single files to send to the browser. This is accomplished using the Sprockets library.
The mechanism for achieving this involves parsing the ./app/assets/javascripts/application.js file and looking for Sprockets directives that will tell Sprockets where to find relevant files.
A brand new application.js file within a newly generated Rails application looks like this:
// FIXME: Tell people that this is a manifest file, real code should go into discrete files
// FIXME: Tell people how Sprockets and CoffeeScript works
//
//= require jquery
//= require jquery_ujs
//= require_tree .
These look like comments to JavaScript but are treated by Sprockets as directives telling it how to build the single application.js that will be delivered to the client. You can probably guess that it is the require_tree
line that is adding in your JavaScript files.
There does not appear to be a wealth of documentation regarding the Sprockets directives. However, the source code is well documented and explains the available directives very well.
The require_tree
directive recursively includes all files within the app/assets/javascripts directory. You can therefore achieve what you want by creating a sub-directory and placing the files you do not want included in there. You can then change require_tree
to require_path
.
The alternative to this would be to manually manage the files that are included by Sprockets on an individual basis, using require filename
for each required JavaScript file.
来源:https://stackoverflow.com/questions/6138041/rails-3-1-the-public-directory-no-longer-serves-js-assets-how-to-load-an-addit