简体   繁体   中英

Rails Asset-pipeline policy

quick example,

make a new rails project, and if we look in to app/assets/javascripts/application.js

it says,

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

in default.

I added foo.js, bar.js in app/assets/javascripts/

and if i run the app, this asset-pipeline

loads foo.js, bar.js in every-pages even i don't need to use in most of the pages.

Is this a right structure?

What about

change to require_self

and use javascript_include_tag and load the js files manually when i need?

Isn't this a better way?

Why Rails asset pipeline default policy is always loading every js files even i dont need?

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

Notice the last require_tree . which means, what ever javascript files currently present inside your app/javsacript folder will be auto loaded. So, in reply to your first question, Yes it's a right structure. Js files inside javascript folder will get auto loaded.

You have kept the js file inside js folder means, in your project you are going to use it :)

In production: When you precompile your assets in production machine, all your js,css will be precompiled into a single application.css & application.js file, so we don't need to bother about loading each manually.

Browsers usually cache assets files.

Therefore it might make sense to deliver one huge assets file to the browser when the user visits the application for the first time. All following request (even for other pages) will be faster, because the browser will not have to reload other small assets.

But it depends: If you have large javascript libraries that are only rarely used in your app, then it might be better to deliver that files only on that special pages.

I know it is an old question but this answers could help someone.

If you need to add an asset just in a specific place you need to add it to the precompile array. In Rails 3 you need to modify config/application.rb file by adding the asset in this way:

config.assets.precompile += %w( foo.js bar.js )

In Rails 4 and 5 you need to modify config/initializers/assets.rb file in this way:

Rails.application.config.assets.precompile += %w( foo.js bar.js )

Don't forget to restart the server.

This article is an excellent resource to learn about Asset Pipeline.

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