Facebook Like Box social plugin doesn't work with Turbolinks

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 20:33:15

The link you have posted in original question is quite nice. It asks us to create three functions:

1) saveFacebookRoot: This is needed so that the div#fb-root can be restored at a later point. This is called upon page:fetch. page:fetch is called while the DoM is still of the old page. i.e: new page has not replaced the old page

2) restoreFacebookRoot: This is needed to that the div#fb-root can be appended back to the page. It is called on page:change. page:change is called when the new DoM is available.

3) There is minor typo in there. We need to call this in page:load

FB.XFBML.parse() // Correct

Instead of :

FB?.XFBML.parse() // InCorrect

Remember that when the page is first reloaded, only the page:change is called out of these three.

The trick here is the use of global variables fb_root and fb_events_bound. These must be accessible in all other pages, but this is the reason why we hate turbolinks in the first place.

References: http://reed.github.io/turbolinks-compatibility/facebook.html

Install observejs:

gem 'observejs'

Then add tag to the widget:

<div as="FB" class="fb-comments" data-href="<%= request.original_url %>"></div>

Then create a new script in javascripts folder (fb.coffee in my example):

ObserveJS.bind 'FB', class
  root: document.createElement('div')
  @::root.id = 'fb-root'

  loaded: =>
    if !document.body.contains(@root)
      document.body.appendChild(@root)

    if FB?
      FB.XFBML.parse()
    else
      @initialize()

  initialize: =>
    js = document.createElement('script')

    script = document.getElementsByTagName('script')[0]
    js = document.createElement('script')
    js.id = 'facebook-jssdk'
    js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=YOUR_APP_ID&version=VERSION_OF_API"
    script.parentNode.insertBefore(js, script)

Include the js files in your application.js

//= require observejs
//= require fb
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!