Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am having trouble with the window.onload and document.onload 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:

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 myParagraph is not loaded (and so the DOM seems incomplete).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <script type="text/javascript">
            window.onload = doThis();
            // document.onload gives the same result

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

    <body>
        <p id="myParagraph">Nothing is here.</p>
    </body>
</html>

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 window.onload set a timer for half a second to run doThis(), but this seems like an inelegant solution, and doesn't answer the question of why window.onload 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.

Is there a more appropriate event to use?

like image 675
David Mason Avatar asked Mar 20 '10 23:03

David Mason


2 Answers

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

like image 85
dgk Avatar answered Oct 07 '22 18:10

dgk


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.

like image 29
Li0liQ Avatar answered Oct 07 '22 18:10

Li0liQ