Rails 3.1: The public directory no longer serves js assets. How to load an additional js file after page is loaded?

余生长醉 提交于 2019-12-03 00:48:13

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.

Steve Weet

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!