views:

57

answers:

2

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) functions?

+1  A: 

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.

meder
That's understandable, but if i move the script right after the closing p tag, will that still work?
Salman A
Yes, that's what I meant by "you are injecting it after the element in the markup directly"
meder
+1  A: 

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 :)

Marko