Luke
Luke

Reputation: 3541

How does this javascript snippet work?

I wrote myself a Javascript function for appending Javascript files to the DOM, I'm fairly new to javascript and as such my solution was fairly verbose. So after a little googling I found this seemingly really cool trick for appending javascript files. Now I'm reluctant to replace my code with the cool new trick till I fully understand how it functions.

Here's the new code.

!function(b){function c(){if(d=e.shift())a=b.body.appendChild(b.createElement("SCRIPT")),a.onload=c,a.src=d}var e=[
  'https://www.google.com/jsapi?key=MY_API_KEY',
  'https://apis.google.com/js/client.js?onload=initPicker'
],a,d;c()}(document);

Please could someone clear up just what is happening here?

Upvotes: 0

Views: 272

Answers (2)

Luke Woodward
Luke Woodward

Reputation: 64949

I believe the code you've presented does the same as the following, which I hope is more readable:

function loadAllJavaScriptFiles() {
    function loadNextJavaScriptFile(){
        var nextUrl = urls.shift();
        if (nextUrl) {
            var scriptElement = document.body.appendChild(
                                    document.createElement("SCRIPT"));
            scriptElement.onload = loadNextJavaScriptFile;
            scriptElement.src = nextUrl;
        }
    }

    var urls = ['https://www.google.com/jsapi?key=MY_API_KEY',
                'https://apis.google.com/js/client.js?onload=initPicker'];
    loadNextJavaScriptFile();
}

loadAllJavaScriptFiles();

a is now scriptElement, function c is now loadNextJavaScriptFile, d is now nextUrl and e is now urls. b was only used to abbreviate document. The outer function never had a name; I've called it loadAllJavaScriptFiles.

The snippet iterates through a number of URLs that presumably return JavaScript code, and creates <script> elements to load this JavaScript code onto the page. The JavaScript is loaded one URL at a time in the order specified in urls: the onload handler for one script file is used to trigger the process of loading the next.

The inner code is wrapped in an immediately-invoked function expression. The code in this method runs immediately, and because it's inside a function it avoids changing the values of any variables in your own JavaScript code that happen to have the same names.

Upvotes: 5

Oday Mansour
Oday Mansour

Reputation: 234

Here's the code slightly cleaned up.

  function c(){
    var e=['https://www.google.com/jsapi?key=MY_API_KEY', 'https://apis.google.com/js/client.js?onload=initPicker']
    var a,d;
    if(d=e.shift()) {
      a=document.body.appendChild(document.createElement("SCRIPT"))
      a.onload=c
      a.src=d
    }
   }

I'm guessing it will iterate over the elements in e and create SCRIPT elements for them in the document.

Do you have any additional documentation to this snippet?

Upvotes: 2

Related Questions