javascript execution order when appended to dom -
so found link gives explanation of how scripts loaded:
http://www.html5rocks.com/en/tutorials/speed/script-loading/
but i'm having trouble understanding happens if this:
<script> var script = document.createelement("script"); script.src = "//www.domain.com/script.js"; document.getelementsbytagname("head")[0].appendchild(script); </script> <script> console.log(myvar); </script>
script.js contains e.g.
var myvar = 'foobar';
so question is... since script.js
appended in separate script tag, guarantee script.js
loaded , executed before console.log()
?
from website linked:
scripts dynamically created , added document async default, don’t block rendering , execute download, meaning come out in wrong order. (emphasis theirs).
this means execution order not guaranteed scripts have been added page via javascript (as in example above).
if want execution deterministic, you'll need manually disable async
property:
var script = document.createelement("script"); script.src = "//www.example.com/script.js"; script.async = false; // overwrite default document.getelementsbytagname("head")[0].appendchild(script);
Comments
Post a Comment