Handling fbAsyncInit? - Use $.Deferred()

- - | Comments

I’m excited to have come across a straightforward example of a practical usage of $.Deferred that has nothing to do with ajax calls.

I’ve seen an assortment of hacks to handle the complexity needed handle what code needs to be run after the Facebook JS SDK has been loaded onto a web page.

There are long lists of callbacks.

There are global booleans.

There are global function references, just to allow for two callbacks.

You don’t have to manually keep track of whether or not the facebook initalization callback has been called. You don’t have to manually handle overwriting the global function fbAsyncInit with references to all the other functions that you need to execute. Using a deferred object is the best way to address these issues, and can even keep you from adding any more global variables than needed.

The plan to tackle this problem is to create a deferred object that is fulfilled when the facebook SDK has finished loaded. Add callbacks wherever you need in your application to this deferred object. Once the SDK has loaded, all of the callbacks will fire, and any callbacks that are added after the SDK loads, will be fired immediately.

Once you have this in your application, anywhere after it, you can add functions that will be executed after the SDK has loaded by using window.fbAsyncInit.fbLoaded.done(callback);

Also, using this method, you can write code that waits on multiple asynchronous events using jQuery’s $.when(). A quick google should have you setup with a lot of information on how to do that.

This post was slightly inspired by reading this post on Deferred method combinators, so you will probably find that a good read if you like this. Please let me know if you have any questions on twitter.

Comments