I’m just starting to play with the facebook API. I have a basic “Hell World” application that just shows the logged in username. It works great when I have the FB.init() function inline (shows the “Login using facebook” button and works). However, I tried creating a JS file called “Facebook.js” and putting the init() in there and now I just see plain text that says “Login using facebook” and obviously, it doesn’t work.
Is it possible to do this? Am I missing something stupid? (probably YES to both)
[————- index.aspx ———————————————————–]
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Scott's test application</title>
<script src="JS/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script src="JS/facebook.js" type="text/javascript"></script>
</head>
<body>
<div id="fb-root"></div>
<div>Welcome <span id="guest" class="UserNameWelcome">Guest</span><span id="name" class="UserNameWelcome"></span>!</div>
<div><img src="" alt="Avatar" id="image"/></div>
<fb:login-button>Login with Facebook</fb:login-button>
</body>
</html>
[————- facebook.js ———————————————————–]
FB.init({
appId: 'myappid', cookie: true,
status: true, xfbml: true
});
FB.api('/me', function (user) {
if (user != null) {
var image = document.getElementById('image');
image.src = 'https://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
} else {
$('#image').hide();
$('#name').hide();
}
});
You don’t have to have everything in the body, but you do have to ensure that all.js is fully loaded before you call any FB functions. Inside facebook.js, you could wrap the FB.init and FB.api calls inside a function called something like start_fb(), and then call start_fb either from within window.onload or window.fbAsyncInit event handler. fbAsyncInit is automatically triggered when all.js has finished loading, but window.onload is slightly safer since it also ensures that all the dom elements are in place like fb-root.