3

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?

shaunshd
  • 95
  • 5
  • please, post the code you use to append your js file – Fabrizio Calderan Apr 22 '12 at 09:01
  • I am not actually doing any dynamic loading of a JS file. I was just wondering if there's is someway we can control when our loaded file gets executed. – shaunshd Apr 22 '12 at 09:05
  • I think it depends on the way you are injecting the script tag. Try some code on your browser, open up Firebug, `console.log` some debug infos & see what's going on in `console` & `network` panel – pomeh Apr 22 '12 at 12:19

4 Answers4

3

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.

AHM
  • 5,145
  • 34
  • 37
  • Can you elaborate on how to call the dynamically inserted script ? For example, if I call a script using onload() e.g.: that inserts another script into the head. How do I call a function in the inserted script ? I won't know when its loaded. – Rahul Iyer Sep 09 '14 at 08:23
  • The trick is that you do it the other way around. So, in you main script you define a global method named something like `resultReady`, and then at the bottom of the script inserted by `displayResult()` you call the `resultReady` function. – AHM Sep 09 '14 at 10:08
3

What happens when a JavaScript file is dynamically loaded ( very simplified, no checks ):

  1. the file is loaded;
  2. if there is function call e.g. doSomething() or (function(){...})(), the code is executed(of course you must have the definitions);
  3. if there are only function definitions, nothing is happening until the function call.

See this example: 3 files are loaded, 2 are executed immediately, 1 is waiting the timeout.

Edit:

The script tag can be placed anywhere in the page. Actually it is better to be placed at the end of the page if the onload event is not used (yahoo speed tips).

With HTML5 JavaScript has web workers MDN MSDN wikipedia.

Bakudan
  • 19,134
  • 9
  • 53
  • 73
1

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.

Starx
  • 77,474
  • 47
  • 185
  • 261
  • i believe the question was how does the flow of code happen when adding a file dynamically rather than how to add dynamically. – Amit Apr 22 '12 at 12:21
  • This is not *that* simple http://paulirish.com/2011/surefire-dom-element-insertion/ – pomeh Apr 22 '12 at 12:21
  • @Starx great. I've updated my comment also after your first edit where you didn't answer the question :) – pomeh Apr 22 '12 at 12:28
-3

Here is some code you can try to get an answer to your question.

<script>
var s = document.createElement('script'), f = 1;
s.src="http://code.jquery.com/jquery-1.7.2.js";
document.head.appendChild(s)
s.onload = function(){
  console.log(2);
  f = 0    
}
while(f){
    console.log(1);
}
</script>

This code should ideally print a 2 when the script loads, but if you notice, that never happens ​

Note: This WILL kill you browser!

Amit
  • 3,952
  • 7
  • 46
  • 80
  • while(f) - this really seems to be the killing part. – Bakudan Apr 22 '12 at 12:17
  • indeed it is. I am using it to show how the execution of JS works. Since the browser is stuck in the while, it will never call the onload event. – Amit Apr 22 '12 at 12:18
  • I seriously dont like the while part – Starx Apr 22 '12 at 12:24
  • 1
    -1 this doesn't answer the question, and it doesn't really demonstrate anything either. It is just malicious code... – AHM Apr 22 '12 at 12:25