开发者

When to use dom:loaded / document.ready events

When I use methods that "append" data to existing elements using prototype/jquery, is it a good practice to wrap such logic inside document.observe("dom:loaded", foo)/$(document).ready(foo) funct开发者_JS百科ions?


Without a ready/loaded event, your code won't fire unless it's at the bottom of the page. This is because the elements don't exist when the code gets read from the <head> section (which executes before the body).

Try this:

$("body").animate({'background-color', '#ff0000'}, 2000);

And then try this:

$(document).ready(function() {
    $("body").animate({'background-color', '#ff0000'}, 2000);
});

You'll see what I mean :)


Well, considering referencing elements before DOM/window ready will not work unless it's the html element or you are injecting it after the element in the markup directly, yes it's the only way to really get it done.

<!doctype html>
<html>
    <head>
        <script>alert( document.getElementById('foo') );</script>
    </head>
    <body>
        <p id="foo"></p>
    </body>
</html>

The above would fail and return null.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜