From: http://developers.facebook.com/docs/guides/web/
(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 = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
2 questions:
- Why is the code used to load the FB SDK inside a self-invoking closure?
- What part of the code actually makes the SDK load asynchronously?
The function is self calling so as to not polute the global namespace. It could have very eaisly have been written as follows:
But then you’ve got an object called loadScript floating around at the global scope level, which would conflict with any other libraries that also have a variable or function called loadScript.
It’s asynchronous because it inserts a script element into the DOM dynamically, which is an asynchronous operation. Take a look at this article for a deeper discussion, http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
Also, that’s not a closure, as there isn’t a function inside the function. A closure is a function that maintains state of it’s environment. In any event, that distinction isn’t hugely important for this question.