开发者

Is there a load event for HTML Body element? I can't seem to get it to work - show an alert

I am trying to attach a listener for the HTML body's load event. But the code doesn't seem to run (event not fired). Is there a load event for the body element? If yes, is the code below correct? Rig开发者_高级运维ht now I just want it to work in Firefox.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Testing</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <p>Hello, World!</p>
    </body>
</html>

script.js

window.onload = function() {
    document.body.addEventListener('load', function() {
      alert("Body has loaded");
    }, true);
}

I know I can do it with jQuery's $(document).ready(); But I want to learn the native DOM methods. Also, I don't want to use <body onload="">. I want to attach the event the way I have shown, at runtime.


There is a load event on <body>, but it will already have fired by the time you add the listener in window.onload.

Using window.onload itself is fine: when that fires, you know the entire page has already loaded. The idea of $(document).ready() is that sometimes it can fire earlier than window.onload, which waits for all the page's resources (eg images) to load before firing.

How to detect the body content being loaded before window.onload fires is quite a complex story, which is why frameworks like jQuery hide it all under their own event. On modern browsers you can do it by listening for the DOMContentLoaded event. On some browsers such as IE there are some ugly browser-specific hacks to guess that the body content is loaded; on older browsers you have no choice but to fall back to window.onload.

To avoid having to implement this sort of complex code you can try just putting a hook call in at the end of the document:

<script type="text/javascript">
    setTimeout(initialiseThings, 0);
</script></body></html>

(The setTimeout being there to allow the browser to pick up the </body> tag, finishing loading the body element and avoiding problems in IE if you try to appendChild onto <body> in your initialisation code before the body is closed. You can omit the timeout if you're not doing anything like that.)


IFAIK is the <body onload=""> the same event as window.onload so your second function is "to late". BTW: the jQery function is way smarter: The browser calls window.onload if every resource is loaded completely. The jQuery function is called when the document (the html) is loaded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜