[removed] seems to trigger before the DOM is loaded (JavaScript)

后端 未结 5 1461
我在风中等你
我在风中等你 2020-11-28 13:45

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 loa

相关标签:
5条回答
  • 2020-11-28 14:17

    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.
      });
    
    0 讨论(0)
  • 2020-11-28 14:21

    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.

    0 讨论(0)
  • 2020-11-28 14:29

    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

    0 讨论(0)
  • 2020-11-28 14:34

    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

    0 讨论(0)
  • 2020-11-28 14:39

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

    0 讨论(0)
提交回复
热议问题