I'm having a hard time trying to load fast the javascript Facebook SDK into my rails 4 application. Is there a good way to make it work correctly with turbolinks?
if i add this code on my JS application assets. It's not working properly due to turbolinks:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'YOUR_APP_ID', // App ID from the app dashboard
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK asynchronously
(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/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
thanks
Quoting this answer
From: https://gist.github.com/6temes/52648dc6b3adbbf05da3942794b97a00
I followed the solution suggested by @gallonallen with some small modification. just created a file called
turbo.js
with following content:And added
//= require turbo
in application.js before//= require query
and it started working for me. I am usingrails 4.2.6
andruby 2.3.1
withturbo links 5
. For me, prior to fix, turbo links was working on my local but not when deployed to staging or prod.If you're putting your Facebook JS code at the end of your view, use
flush
in your controller action to ensure it's fully reloaded properly with Turbolinks:Worked like a charm.
You will find the proper solution for integrating the Facebook SDK with Turbolinks here :
http://reed.github.io/turbolinks-compatibility/facebook.html
I was having a problem with the Like Box not loading when I navigate between pages using turbo links. My solution was to create a
social.js.coffee
in myassets/javascripts
folder. In this file it simply hasI know its a lot to put in it's own file ;-), but the idea was that I know google analytics, twitter, and others will have the same conflicts and this will be a nice place to house those solutions as well.