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

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.

Leave a Comment