Skip to content

Instantly share code, notes, and snippets.

@mupkoo
Last active March 15, 2018 18:26
Show Gist options
  • Save mupkoo/0741aa782e9678be1d40 to your computer and use it in GitHub Desktop.
Save mupkoo/0741aa782e9678be1d40 to your computer and use it in GitHub Desktop.
Facebook Like snippet for Turbolinks
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()
<div class="fb-like" data-href="{URL}" data-layout="button_count" data-action="like" data-show-faces="false" data-share="false"></div>
@sanyam-j
Copy link

sanyam-j commented Jan 7, 2017

Not working for me. Do i need to call Facebook.load() on every page change?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment