Using Font Awesome 5 in the Rails Asset Pipeline with Turbolinks

Font Awesome is a pretty indispensable part of any project for me and I finally decided to show my appreciation and buy a year's pro subscription. I was looking forward to using the "light" icons (as far as I can tell these are the only icons which are limited to the pro subscription), but I soon hit some road blocks on setting it up in the Rails asset pipeline.

If you have been following Font Awesome's development, you have probably seen the shiny new version 5 which changes the recommended way to include the icons. The How to Use section provides some great documentation, but sadly a Rails walkthrough is not to be found.

So, here's what we're going to set up:

  • Download and serve only the light theme to save on file size
  • Fix a gotcha when using Turbolinks that keeps icons from displaying on every page

Download and save files

When you download Font Awesome and unzip the files, you will see quite a few folders in the tree. The two you need are:

  • fontawesome-pro-#{version}/svg-with-js/js/fontawesome.js
  • fontawesome-pro-#{version}/svg-with-js/js/fa-light.js (or whatever specific style you want to include)

Copy these two files into your app/assets/javascripts/ folder. I'm, assuming that you are going to run these through Uglifier so there's no reason to opt for the minified versions.

To test that this is working, throw an <i class="fal fa-user"></i> onto a page and see it display.

First and foremost, credit to Michael Minton for posting a coffee-script example of how to do this (he also has a solution for layout shifting you should check out).

It won't be too long before you realize that you sweet Font Awesome icons are not displaying on every page, but only the first time the page is loaded (or refreshed). The problem (or complication if you prefer less accusatorial language) is Turbolinks. To fix this, you want Font Awesome to re-render the icon whenever the turbolinks:load event is triggered.

Add a new file with the following (note: I added jQuery back into my project to use with Bootstrap):

(function() {
  $(document).on("turbolinks:load", function() {
    return FontAwesome.dom.i2svg();
  });

}).call(this);

Alternatively, if you are using CoffeeScript, you can use Michael's example linked above.

So, there you go, Font Awesome Pro in the Rails asset pipeline using just the files you need. You could get the file size even smaller if you go through and delete the SVGs of the icons you aren't using, but I'll leave that up to you.