How to embed JavaScript / CSS in an HTML page using the Rails resource pipeline?

I am developing a web page whose content is fully generated using client-side JavaScript. The sole purpose of index.html is to access JavaScript and CSS documents that are created using the Rails resource pipeline. To avoid additional requests, I would like to embed these JavaScript and CSS into production.

How to embed JavaScript and CSS content that is created using the resource pipeline?

+6
source share
3 answers

You can use Rails.application.assets to get the contents of assets after precompilation. Add this to your index.html.erb :

 <style type="text/css"> <%= raw Rails.application.assets['application.css'].to_s %> </style> <script type="text/javascript"> <%= raw Rails.application.assets['application.js'].to_s %> </script> 

Do not forget raw , otherwise " will be changed to &quot; etc.

Please note that this is not compressed; for production, you probably want to embed compressed code. To do this, add the gem 'uglifier' to your Gemfile, run the package and use this:

 <%= raw Uglifier.new(:copyright => false).compile Rails.application.assets['application.js'].to_s %> 
+26
source

You can also use: Rails.application.assets.find_asset('api.css').to_s

+2
source

You probably do not want to embed these assets for productivity in the production process. You will probably be much better off listening to them from a CDN like CloudFront, and caching them along the way.

This should provide a better performance improvement than cutting 2 HTTP requests that are rarely executed.

-1
source

All Articles