For single page applications (React in my case)
In single page applications you have less control about the order in which the code will run. Sometimes the script will have loaded by the time you call your code, sometimes not.
To make it work regardless of whether the facebook script has already loaded or not, I do a check whether the FB
global variable is already defined at the moment of running the code. If so, I just do a normal initialize, otherwise I provide the callback.
This is my code:
export function initializeFacebookSdk() {
/* Asynchronous flow: if the global 'FB' variable is still undefined,
then the facebook script hasn't loaded yet, in that case, provide
a global callback that will be called by the facebook code. If the
variable is already present, just call the code right away and forget
about the callback. */
if(window.FB === undefined) {
console.log('FB undefined -> provide callback');
window.fbAsyncInit = function() {
initialize();
};
}
else {
console.log('FB defined -> call init right away');
initialize();
}
function initialize() {
window.FB.init({
appId : '492331311256888',
cookie : true,
xfbml : true,
version : 'v3.2'
});
}
}
In my html file I just provide the script given by facebook, and in my code I can call initializeFacebookSdk()
wherever and whenever I want:
<!DOCTYPE html>
<html lang="en">
<head>
<title>My application</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<script>
(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 = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div id="root"></div>
</body>
</html>
https://
explicitly to thejs.src
URL