Font Awesome 5’s SVG with JS is slick and modern. It uses javascript to find all the <i> tags with icons (e.g., fas fa-camera) and replaces them with an <svg> tag. The best part is the SVG icons will respect all your CSS styles like size and color. Truly awesome stuff. However, there is a problem. Out of the box this won’t play nice with Rails 5 and Turbolinks. What will happen is the initial page load will correctly show the icons but after clicking a link Turbolinks will reload the page but not your icons. In this article I’ll walk you through a few steps to fix this.

Setting up Font Awesome 5

These instructions are current as of v5.0.6. Check https://fontawesome.com/get-started for the latest instructions.

In your application.html.erb inside the <head> tag include a link to Font Awesome from their free CDN.

<head>
    ...
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
</head>

Create an init script

We’re going to create a small script to call into Font Awesome’s API and force it to re-render the icons everytime the turbolinks:load event fires.

Create a new file called fontawesome-init.coffee in app/assets/javascripts/ with the following:

$(document).on "turbolinks:load", ->
  FontAwesome.dom.i2svg()

Important!

If your application.js doesn’t have //= require_tree . then you’ll need to add //= require fontawesome-init.

Prevent layout shifting

While optional, this next step will prevent your layout from constantly resizing as the intial view is loaded and the icons are being rendered. Font Awesome 5 adds the fontawesome-i2svg-pending class to the <html> tag while it’s rendering icons. Using a variant of the instructions here, we can take advantage of this and hide the <body> tag until the icons are rendered and that class is removed.

Add the following to your application.scss:

.fontawesome-i2svg-pending body {
	display: none;
}

You now have Rails 5 with Turbolinks working with Font Awesome 5’s SVG with JS approach. 🍰