Mirko Akov
May 29, 2014 · 1 min read

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.

# facebook.coffee
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")
facebookScript.id = 'facebook-jssdk'
facebookScript.async = 1
facebookScript.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&appId=#{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
$(document)
.on('page:fetch', Facebook.saveRoot)
.on('page:change', Facebook.restoreRoot)
.on('page:load', ->
FB?.XFBML.parse()
)
Facebook.eventsBound = true @saveRoot = ->
Facebook.rootElement = $('#fb-root').detach()
@restoreRoot = ->
if $('#fb-root').length > 0
$('#fb-root').replaceWith Facebook.rootElement
else
$('body').append Facebook.rootElement
@appId = ->
'APP-ID'
Facebook.load()

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.

Evermore

Development consultancy, specialised in building custom web solutions and applications since 2006. Visit us at: http://weareevermore.com

Mirko Akov

Written by

Full stack developer @weareevermore #ruby #elixir #ember.js

Evermore

Evermore

Development consultancy, specialised in building custom web solutions and applications since 2006. Visit us at: http://weareevermore.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade