title: window.onload seems to trigger before the DOM is loaded (JavaScript)
body: <p>I am having trouble with the <code>window.onload</code> and <code>document.onload</code> events. Everything I read tells me these will not trigger until the DOM is fully loaded with all its resources, it seems like this isn't happening for me:</p>
  
  <p>I tried the following simple page in Chrome 4.1.249.1036 (41514) and IE 8.0.7600.16385 with the same result: both displayed the message "It failed!", indicating that <code>myParagraph</code> is not loaded (and so the DOM seems incomplete).</p>
  
  <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt;
      &lt;head&gt;
          &lt;script type="text/javascript"&gt;
              window.onload = doThis();
              // document.onload gives the same result
  
              function doThis() {
                  if (document.getElementById("myParagraph")) {
                      alert("It worked!");
                  } else {
                      alert("It failed!");
                  }
              }
          &lt;/script&gt;
      &lt;/head&gt;
  
      &lt;body&gt;
          &lt;p id="myParagraph"&gt;Nothing is here.&lt;/p&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>I am using more complex scripts than this, in an external .js file, but this illustrates the problem. I can get it working by having <code>window.onload</code> set a timer for half a second to run <code>doThis()</code>, but this seems like an inelegant solution, and doesn't answer the question of why <code>window.onload</code> doesn't seem to do what everyone says it does. Another solution would be to set a timer that will check if the DOM is loaded, and if not it will just call itself half a second later (so it will keep checking until the DOM is loaded), but this seems overly complex to me.</p>
  
  <p>Is there a more appropriate event to use?</p>