Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed JavaScript/CSS in HTML page using Rails' asset pipeline?

I'm developing a webpage, which content is fully generated with client-side JavaScript. The only purpose of index.html is to refer to JavaScript and CSS documents, which are generated with Rails' asset pipeline. To avoid extra requests, I'd like to inline those JavaScript and CSS in production.

How to inline JavaScript and CSS content which is generated with asset pipeline?

like image 430
skalee Avatar asked Nov 21 '12 00:11

skalee


People also ask

Where do I put JavaScript code in rails?

The directory structure for JavaScript has changed to the app/javascript/packs/ folder. In that folder you will find the application. js file, which is just like the application.

How do I enable JavaScript in rails?

1 Import maps js or Yarn to function. If you plan to use Rails with importmap-rails to manage your JavaScript dependencies, there is no need to install Node. js or Yarn. When using import maps, no separate build process is required, just start your server with bin/rails server and you are good to go.


2 Answers

You can use Rails.application.assets to get the content of the assets after precompilation. Add this in 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>

Don't forget the raw, otherwise " will be changed into &quot; etc.

Note this isn't compressed; for production, you will probably want to inline compressed code. To do so, add gem 'uglifier' to your Gemfile, run bundle, and use this:

<%= raw Uglifier.new(:copyright => false).compile Rails.application.assets['application.js'].to_s %>
like image 174
Baldrick Avatar answered Oct 14 '22 08:10

Baldrick


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

like image 21
Ariel Avatar answered Oct 14 '22 07:10

Ariel