Code Whisperer Code Whisperer - 3 months ago 16
Javascript Question

How Can This Unnamed Function Be Called?

I was reviewing the script provided by Facebook in order to run it's authorization. I ran into this puzzling bit of code:

(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/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));


As an unnamed function in its own scope, it would seem like this could never be called, but there it is, included in the boilerplate script.

What is going on here?

Answer

The function is an Immediatly Invoked Function Expression

(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/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));

If you notice the function has 3 arguments d, s, id then you will notice the function body.. At the end it calls it self passing in the args document, script, facebook-jssdk.

All this function does is creates a script such as.

<script id="facebook-jssdk" src="//connect.facebook.net/en_US/sdk.js"></script>

and inserts it before the first script tag in the document.