Anubix Anubix - 9 months ago 28
CoffeeScript Question

Facebook plugin page in Rails Turbolinks doesn't load

in my Rails app I am loading Facebook plugin page, but because of turbolinks it doesnt load each page (only sometimes). I tried this script on this page , but now it never loads. What did I do?

I created facebook.coffee with this script:

$ ->
loadFacebookSDK()
bindFacebookEvents() unless window.fbEventsBound

bindFacebookEvents = ->
$(document)
.on('page:fetch', saveFacebookRoot)
.on('page:change', restoreFacebookRoot)
.on('page:load', ->
FB?.XFBML.parse()
)
@fbEventsBound = true

saveFacebookRoot = ->
if $('#fb-root').length
@fbRoot = $('#fb-root').detach()

restoreFacebookRoot = ->
if @fbRoot?
if $('#fb-root').length
$('#fb-root').replaceWith @fbRoot
else
$('body').append @fbRoot

loadFacebookSDK = ->
window.fbAsyncInit = initializeFacebookSDK
$.getScript("//connect.facebook.net/cs_CZ/sdk.js#xfbml=1&version=v2.6")

initializeFacebookSDK = ->
FB.init
appId : 'YOUR_APP_ID'
status : true
cookie : true
xfbml : true


And then in my application.js i just require it.

In view I have this code:

<div id="fb-root"></div>
<div class="fb-page" data-href="https://www.facebook.com/mypage/" data-tabs="timeline" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><div class="fb-xfbml-parse-ignore"><blockquote cite="https://www.facebook.com/mypage/"><a href="https://www.facebook.com/mypage/">MyPage</a></blockquote></div></div>


Facebook plugin page isn't loading. Don't you know why? I was looking on appId, but in plugin page its not included.

Answer Source

This worked for me ... Some sort of combination between Facebook's docs and the script on the page you linked

$ ->
  loadFacebookSDK()
  bindFacebookEvents() unless window.fbEventsBound

bindFacebookEvents = ->
  $(document)
    .on('page:fetch', saveFacebookRoot)
    .on('page:change', restoreFacebookRoot)
    .on('page:load', ->
      FB.XFBML.parse()
    )
  @fbEventsBound = true

saveFacebookRoot = ->
  if $('#fb-root').length
    @fbRoot = $('#fb-root').detach()

restoreFacebookRoot = ->
  if @fbRoot?
    if $('#fb-root').length
      $('#fb-root').replaceWith @fbRoot
    else
      $('body').append @fbRoot

loadFacebookSDK = ->
  ((d, s, id) ->
    js = d.getElementsByTagName(s)[0]
    fjs = d.getElementsByTagName(s)[0]
    return if d.getElementById(id)
    js = d.createElement(s)
    js.id = id
    js.src = "https://connect.facebook.net/es_LA/sdk.js#xfbml=1&version=v2.5"
    fjs.parentNode.insertBefore(js, fjs)
  )(document, 'script', 'facebook-jssdk')

initializeFacebookSDK = ->
  FB.init
    # appId : 'YOUR_APP_ID'
    status : true
    cookie : true
    xfbml : true

The difference is in the loadFacebookSDK function. Notice that as I commented in the question, $.getScript() removes the query/parameters part of the request.