Executing dynamically loaded JS files

I understand that JS is single-threaded and synchronously executed. Therefore, when I add a file to my browser header, this file is executed as soon as it occurs. Then it moves on to the next script tag and executes this file. My question is that I am adding the js file dynamically to the HTML header tag. How does the browser execute this file? It is like a file is being executed as soon as the file is loaded wherever the current execution is being executed. Or can we control how this file is executed?

+3
source share
4 answers

When the script loads, it will be executed as soon as possible. That is, if any other javascript function is executed, for example, a click manipulator or something else, it will be allowed to complete first, but this is set because, as you say, JavaScript usually runs in a single thread in browsers.

You cannot control this part of the script loading, but you can use this template - strongly inspired by JSONP:

script inserted:

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

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

script on the main page:

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

- ready, , script, . , , script , , init , .

+3

, JavaScript ( , ):

  • ;
  • , . doSomething() (function(){...})(), (, );
  • , .

. : 3 , 2 , 1 -.

Edit:

script . , onload ( Yahoo).

HTML5 JavaScript - MDN MSDN wikipedia.

+3

,

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)

?

script DOM

, , , ?

, ?

, onload, .

+1
source

Here is the code you can try to get the 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 2 when the script loads, but if you notice that it never happens

Note. This will delete your browser!

-3
source

All Articles