I am trying to add a Facebook Like button to a widget that I am creating. The code that I use to add the Facebook like button to my page is as follows:
widget.html
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '263071593731910',
status : false, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<div id="fb-button"></div>
<script type="text/javascript" src="widget.js"></script>
widget.js
$(function(){
var fb = $(document.createElement("fb:like"));
fb.attr({
href: data.facebook,
send: false,
layout: 'button_count',
width: 70,
'show_faces': false
});
$("#fb-button").empty().append(fb);
FB.XFBML.parse($("#fb-button").get(0));
FB.Event.subscribe('edge.create',changeView);
});
*The changeView function does exist as well in the JavaScript.
When I run the code, I get an error: Uncaught ReferenceError: FB is not defined even though the button is created. The error is pointing to the line containing FB.XFBML.parse code. Is there something I need to do differently in my JavaScript?
The whole point of that big script block starting with
window.fbAsyncInitis that the Facebook SDK gets loaded asynchronously.Even though you’ve got your calls against
FBinside a jQuery document ready callback, that isn’t sufficient to ensure the SDK is loaded when that code is executed.Fortunately,
window.fbAsyncInitexists for exactly that purpose: it won’t be run until the SDK has loaded.From Facebook’s docs: