MartinsB MartinsB - 8 months ago 34
Javascript Question

Facebook share button not loading with Rails turbolinks

I was following Facebook general guidlines to include Share button (Social Plugin)
https://developers.facebook.com/docs/plugins/share-button

_social.html.erb

<div id="fb-root"><div class="fb-share-button" data-href="http://www.example.com" data-layout="button_count"></div></div>


fb_share.js

var fb_share;
fb_share = function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3&appId=xxxxxxxxxxxxxxx";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk');

$(document).ready(fb_share);
$(document).on('page:load', fb_share)


application.js

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require_tree .


The button renders on first page load, works correctly also. But is not rendered when navigating to next page and back.

If I include fb_share.js file in application.js file (before turbolinks) it doesn't show up at all.

Answer Source

The Facebook JS SDK only goes through the HTML document once upon initialization, to look for elements to replace with the FB social plugins.

And trying to embed the JS SDK again, as you are trying by calling fb_share, is useless – because that code is specifically written to not embed it again, if it has been embedded already.

The correct way to get the SDK to parse the document again for content added only later on, is to call FB.XFBML.parse.