window.onload seems to trigger before the DOM is loaded (JavaScript)

Just use window.onload = doThis; instead of window.onload = doThis();


Have you tried using a javascript library instead, e.g. jQuery and it's $(document).ready() function:

  $(document).ready(function() {
      // put all your jQuery goodness in here.
  });

At the time window is loaded the body isn't still loaded therefore you should correct your code in the following manner:

<script type="text/javascript">
    window.onload = function(){
        window.document.body.onload = doThis; // note removed parentheses
    };

    function doThis() {
        if (document.getElementById("myParagraph")) {
            alert("It worked!");
        } else {
            alert("It failed!");
        }
    }
</script>

Tested to work in FF/IE/Chrome, although thinking about handling document.onload too.

As already mentioned, using js-frameworks will be a far better idea.


It's important to understand that () is an operator, just like + or &&. () Takes a function and calls it.

So in that case, doThis is a function object, and () is the operator that calls the function. doThis() combined to together calls doThis, executes it, and evaluates to the return value of doThis

So window.onload = doThis() is basically assigning the return value of doThis to window.onload

And thus, to fix that, you need to reference the function itself, not call it.

Do window.onload = doThis