Connect/Performance Tips

From Facebook Developer Wiki

Jump to: navigation, search

This article discusses some of the more advanced techniques you can use to improve the performance of your Facebook Connect implementations.

Delay Loading the Main JavaScript Library

By default, the Facebook Connect libraries will be loaded on page load and available for use when you call FB.init. However, if your site only uses Facebook functionality in some places, then you can dynamically load the bulk of the library when you need it.

To do so, wrap all Facebook function calls in a call to FB_RequireFeatures. See Initializing and Loading Facebook Connect Features for more information.

Load the FeatureLoader Script Asynchronously

Another way you can improve Facebook Connect performance is to load the FeatureLoader script asynchronously. Once the FeatureLoader script loads, then you can call FB.init.

These examples use the Script DOM Element technique to load the FeatureLoader script without blocking (that is, it's loaded asynchronously). You can use other non-blocking techniques as well.

If you need to use XFBML or other features that manipulate the DOM, you need to place this snippet of code after any XFBML tags. Or you need to implement DOM ready type detection.

<script type="text/javascript"> // This function is called after FeatureLoader is loaded function fbInit() { FB.Facebook.init("<YOUR-API-KEY>", "<PATH_TO_YOUR_CROSS_DOMAIN_RECEIVER>"); } // Load feature loader asynchronously var head = document.getElementsByTagName("head")[0], script = document.createElement("script"), done = false; script.src = 'http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US'; script.onload = script.onreadystatechange = function(){ if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) { done = true; fbInit(); } }; head.appendChild(script); </script>


Using jQuery

You can load the FeatureLoader script asynchronously with jQuery. If you need to use XFBML or other features that manipulate the DOM, you can use $().ready() in the getScript() callback.

<script type="text/javascript"> // prevent jQuery from appending cache busting string to the end of the FeatureLoader URL var cache = jQuery.ajaxSettings.cache; jQuery.ajaxSettings.cache = true; // Load FeatureLoader asynchronously. Once loaded, execute Facebook init jQuery.getScript('http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US', function() { FB.Facebook.init("<YOUR_API_KEY>", "<PATH_TO_YOUR_CROSS_DOMAIN_RECEIVER>"); }); // Restore jQuery caching setting jQuery.ajaxSettings.cache = cache; </script>