Reputation: 3240
This might sound like a silly question, and I tend to use:
$(document).ready(function() { });
But basic question.
Let's say I have a list of elements like this:
<body>
<p>Paragraph</p>
<div>Div</div>
<div id="HelloWorld">Hello, World</div>
<script>
var hw = $('#HelloWorld');
$(document).ready(function() {
// hw is available for me here
});
</script>
<p>Another paragraph</p>
</body>
It seems the div is available, and I don't run into errors, but is there anything technically wrong with this? Not talking perfectly organized code, but just curious about the technical question at hand.
So I suppose the question is:
Is a DOM element considered complete and available as soon as the browser reads it, regardless if the rest of the elements have loaded yet?
Upvotes: 3
Views: 1352
Reputation: 1074268
It seems the div is available, and I don't run into errors, but is there anything technically wrong with this?
No. As long as the script isn't run until after the element exists, you can access it. A script in a script
tag that's after the markup for the element it refers to will consistently, cross-browser, be able to access that element.
Always works:
<div id="foo">...</div>
<script>
$("#foo")...
</script>
Never works:
<script>
$("#foo")...
</script>
<div id="foo">...</div>
Works only because jQuery delays executing the ready
callback:
<script>
$(document).ready(function() {
$("#foo")...
});
</script>
<div id="foo">...</div>
This is one of the reasons for the common recommendation to put script
tags at the end of the document, just before the closing </body>
tag. That way, they have access to all of the elements defined above them. (And they don't delay the initial presentation of the page, which is usually, though not always, what you want...)
Upvotes: 4