Deferred Facebook js.all script loading using jQuery

If you are loading scripts from a number of 3rd party sources, such as Google Analytics, Ads, Twitter, Buzz, and Facebook etc., your page load-time can go through the roof. You can get around these by adding them to the document ready event handler. But the problem is, you may want to run some scripts once the remote script has successfully loaded. For scripts hosted in your domain you can use AJAX, but unfortunately there isn’t general way of doing this for scripts on a different domain.

Some of these third parties, however, trigger ready events for their script when it has completely loaded. Facebook has such a feature for their all.js script. Let’s take a look at how to use it. We’ll use jQuery to defer the script loading.

The event triggered by the all.js script is called fbAsyncInit, and it is attached to the window object. We’ll need to add a handler for this event:
window.fbAsyncInit = function() { alert('Facebook script loaded!'); };

And then we simply have the jQuery $(document).ready event load the Facebook script:
var fbscript = document.createElement('script');
fbscript.type = 'text/javascript';
fbscript.src = 'http://connect.facebook.net/en_US/all.js#xfbml=1';
document.getElementsByTagName('head')[0].appendChild(fbscript);

Now what happens is that, when the page has completed loading the second code block adds a reference to the facebook script, which gets loaded and starts executing. When it is done, it triggers the function we added in the first code block. Of course, you can replace that with something more usefull than a message saying it’s loaded! Or, you can get rid of it all together if you are just interested in the deferred load, and do not need to execute anything after the script has loaded.

Author: Musaul Karim

Software Engineer, Hobbyist Photographer, and a bit of a gadget geek.

Leave a Reply

Your email address will not be published. Required fields are marked *