I have a snipped that is placed inside ANY website, in the middle of the document like in the middle of an article, not inside <head>. This script loads an external script on my domain by appending a <script> tag (pretty much like google analytics snippet does).
My questions is if that script is placed inside the body, does the DOM hasn't already been parsed, so I can safely assume that I can manipulate the DOM when my script is evaluated without waiting for DOMReady event?
I'm asking because theres a big delay when my script start executing and when the DOMReady event fires (see the brown bar). I'm using this DOMReady implementation
The Host Website
<html>
<head>
...
</head>
<body>
Website content
...
<div>
<!-- Snippet -->
<div id="myContainer"></div> <!------(I should be able to query this div) -->
<script type="text/javascript">
function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = 'http://example.com/script.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- Snippet End -->
<div>
More content
...
</body>
</html>
The example.com/ script.js
(function(){
//by this time div#myContainer should exist, right?
var div = document.getElementById('myContainer');
div.innerHTML = "Hello World!";
})();
Some considerations:
- I don't have control over the Host page, it can have anything inside it.
- Support for old browsers are a concern.
- I should be able to append stuff as soon as possible, I can't wait for things like other libraries, and images to finish loading.
- It should reliable work everytime.

Yes that's right. If you have a script tag at the bottom of the body, then by the time your script runs, everything is rendered before that.
W3Schools have a nice article on this subject.
Scripts in
<head>Scripts in
<body>