I am trying to do something that uses the async loading pattern as bellow:
<div id="mydiv">
<script type="text/javascript">
var test = .......;
function() {
var js = document.createElement('script');
js.async = true;
js.src = 'myscript.js';
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(js, first);
})();
</script>
<div>
Then inside myscript.js I work on the assumption that the div with id mydiv is guaranteed available when it myscript.js is executed. Is this assumption valid? It sounds really should be the case. But i sometimes run into situation the code couldn't find the div inside myscript.js.
Also regarding the general page loading. does all the tags get loaded first? what happens when this async loading pattern happens? does it get loaded after all the original tags gets loaded first?
Thanks,
1 Answer 1
Put the script element outside the div element, after it. Elements are created in sequential order, and script elements inside the body are executed as they are created, so this will guarantee that the div will be available when the script is executed.
This also avoids a nasty error on IE where modifying the elements containing a script block from within the script block causes it to refuse to render the page entirely.