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

点点圈 提交于 2019-11-27 14:47:29

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.

dgk

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

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

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.
  });
Lorenz Lo Sauer

It depends where you put the onload function (head or body tag or further down), with internal event binding seeemingly slightly different in different browsers.

See also window.onload vs document.onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!