How to add Facebook like button that works with Turbolinks

After finding a solution to add Google Analytics tracking code, once again I had to face a problem that came with Turbolinks. I was not able to load the facebook script in the head of the page, to prevent it from being loaded with every single request. That’s why, I decided to combine my research into a helpful CoffeeScript class.

To be able to use it, you need to require the file in your application script and load them in the head section of the page. Make sure to replace the APP-ID with yours.

NOTE: The script can be used without Turbolinks as well.

class @Facebook
    rootElement = null
eventsBound = false
    @load: ->
unless $('#fb-root').size() > 0
initialRoot = $('<div>').attr('id', 'fb-root')
$('body').prepend initialRoot
        unless $('#facebook-jssdk').size() > 0
facebookScript = document.createElement("script") = 'facebook-jssdk'
facebookScript.async = 1
facebookScript.src = "//{Facebook.appId()}&version=v2.0"
            firstScript = document.getElementsByTagName("script")[0]
firstScript.parentNode.insertBefore facebookScript, firstScript
        Facebook.bindEvents() unless Facebook.eventsBound
    @bindEvents = ->
if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
.on('page:fetch', Facebook.saveRoot)
.on('page:change', Facebook.restoreRoot)
.on('page:load', ->
        Facebook.eventsBound = true
    @saveRoot = ->
Facebook.rootElement = $('#fb-root').detach()
    @restoreRoot = ->
if $('#fb-root').length > 0
$('#fb-root').replaceWith Facebook.rootElement
$('body').append Facebook.rootElement
    @appId = ->

After you have done this, you can use the HTML5 version of the button. For example:

<div class="fb-like" data-href="{URL}" data-layout="button_count" data-action="like" data-show-faces="false" data-share="false"></div>

Fork the gist to meet your needs.