
When you integrate Facebook social plugins into your website you run into an interesting question: How do you guarantee that the Facebook JavaScript API SDK is loaded when your website's content has been rendered? Is it possible to guarantee that the FB SDK must be loaded when the webpage is done loading?
A developer would use the following standard code straight from Facebook's official developer website:
2 | var js, id = 'facebook-jssdk' , ref = d.getElementsByTagName( 'script' )[0]; |
3 | if (d.getElementById(id)) { return ;} |
4 | js = d.createElement( 'script' ); js.id = id; js.async = true ; |
5 | js.src = "//connect.facebook.net/en_US/all.js" ; |
6 | ref.parentNode.insertBefore(js, ref); |
This code may be different depending on when you download the code on Facebook's developer site.
However is this code really robust? What if while loading the webpage there's a brief stoppage of the internet connectivity? What if the browser fails to receive connect.facebook.net/en_US/all.js from Facebook's CDN? What if the browser gets the Facebook Javascript source code but never executes it?
Let's look at a more robust way to load and execute the Javascript Facebook SDK.
Solution
Let's look at the sample Javascript code below. This code loads the Facebook JS API asynchronously while making sure the API is executed at some maximum number of tries spaced at intervals of some time.
02 | var isFbSdkLoaded = false ; |
05 | window.fbAsyncInit = function() { |
14 | FB.Event.subscribe( 'xfbml.render' , function(response) { |
23 | var loadFbSdkTries = 0; |
25 | if (isFbSdkLoaded || ++loadFbSdkTries > 3){ |
33 | var js, id = 'facebook-jssdk' , ref = d.getElementsByTagName( 'script' )[0]; |
42 | js = d.createElement( 'script' ); js.id = id; js.async = true ; |
43 | js.src = "//connect.facebook.net/en_US/all.js" ; |
44 | ref.parentNode.insertBefore(js, ref); |
49 | setTimeout( function(){loadFbSdk();}, 3000 ); |
Please look at the comments to understand the JavaScript code.
Questions? Let me know! This sample code guarantees that window.fbAsyncInit is executed at some number of tries at most.