Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  75] [ 4]  / answers: 1 / hits: 25826  / 13 Years ago, wed, october 12, 2011, 12:00:00

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?


More From » jquery

 Answers
2

The whole point of that big script block starting with window.fbAsyncInit is that the Facebook SDK gets loaded asynchronously.



Even though you've got your calls against FB inside a jQuery document ready callback, that isn't sufficient to ensure the SDK is loaded when that code is executed.



Fortunately, window.fbAsyncInit exists for exactly that purpose: it won't be run until the SDK has loaded.



From Facebook's docs:




The function assigned to window.fbAsyncInit is run as soon as the SDK
is loaded. Any code that you want to run after the SDK is loaded
should be placed within this function and after the call to FB.init.
For example, this is where you would test the logged in status of the
user or subscribe to any Facebook events in which your application is
interested.



[#89643] Tuesday, October 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lizet

Total Points: 479
Total Questions: 96
Total Answers: 113

Location: Mexico
Member since Sun, Jul 25, 2021
3 Years ago
;