MartinsB MartinsB - 1 year ago 104
Javascript Question

Facebook share button not loading with Rails turbolinks

I was following Facebook general guidlines to include Share button (Social Plugin)


<div id="fb-root"><div class="fb-share-button" data-href="" data-layout="button_count"></div></div>


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); = id;
js.src = "//";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk');

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


//= 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download