April 22, 2012

Execution of dynamically loaded JS files

Question by shaunshd

I understand that JS is single threaded and synchronously executed. Therefore when i add a file to my browser head tag that file is executed as soon as its encountered. Then it goes to the next script tag & executes that file. My question is when I add a js file dynamically to an HTML head tag. How does the browser executes that file?
Is it like that the file is executed as soon as the file is loaded wherever the current execution is. Or is it that we can control how that file is executed?

Answer by AHM

When the script is loaded, it will be executed as soon as possible. That is, if some other javascript function is executing, like a clickhandler or whatever, that will be allowed to finish first – but this is a given because, as you say, in browsers JavaScript normally execute in a single thread.

You can’t control that part of the script loading, but you could use this pattern – heavily inspired by JSONP:

inserted script:

(function () {
    var module = {
        init: function () {
            /* ... */
        }
    }

    ready(module);  // hook into "parent script"
}());

script on main page:

function ready(o) {
    // call init in loaded whenever you are ready for it...
    setTimeout(function () { o.init(); }, 1000);
}

The key here is the ready function that is defined on your page, and called from the script you insert dynmaically. Instead of immediately starting to act, the script will only tell the parent page that it is loaded, and the parent page can then call back to the inserted scripts init function whenever it wants execution to start.

Answer by Starx

Considering a way to do this is

var js=document.createElement('script')
js.setAttribute("type","text/javascript")
js.setAttribute("src", filename)
document.getElementsByTagName("head")[0].appendChild(js); 
// ^ However this technique has been pointed to be not so trusworthy (Read the link in the comment by Pomeh)

But answering your question

How does the browser executes that file?

As soon as the script is added to the DOM

Is it like that the file is executed as soon as the file is loaded wherever the current execution is?

Yes

Or is it that we can control how that file is executed?

Its better if you attach an onload event handler, rather than a nasty tricks.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!