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?
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.
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.
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 "
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 %>
You can also use: Rails.application.assets.find_asset('api.css').to_s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With