4

Fairly new to Jquery here.... but one thing I have been told and being doing, is add my Javascript at the bottom of my page after the html is read.

Now, I see people adding the $(document).ready(function() even when the code is at the bottom of the page. Isn't the DOM being progressively built as the HTML is read? By the end of reading the HTML, shouldn't the DOM be automatically be ready and therefore, what is the point of adding this check?

For example, small demo:

<ul>
    <li id="draggable" class="ui-state-highlight">Drag me down</li>
</ul>

<ul id="sortable">
    <li class="ui-state-default">Item 1</li>
    <li class="ui-state-default">Item 2</li>
    <li class="ui-state-default">Item 3</li>
    <li class="ui-state-default">Item 4</li>
    <li class="ui-state-default">Item 5</li>
</ul>
<script>
alert("In Page");
</script>

</div><!-- End demo -->

<script>
$(function() {
    alert("Dom is READY");
    $( "#sortable" ).sortable({
    revert: true
    });

    $( "#accordion" ).accordion();
});
</script>

The "In Page" always appear first... is it because the HTML is not "big" enough?

abisson
  • 4,365
  • 9
  • 46
  • 68
  • Isn't it kind of like asking "why do I need to wear a belt if I go around holding my pants up all the time?" Maybe a better question is "why do I put all the code at the bottom if it runs based on DOM events?" – dkretz May 26 '12 at 03:42
  • related (but not a dup IMO) http://stackoverflow.com/questions/8717401/is-the-onload-necessary-when-the-code-is-at-the-bottom – ajax333221 May 26 '12 at 05:55
  • @ledorfier - I almost fell out of my chair when I read that ;) That's hilarious. – jamesmortensen May 26 '12 at 06:35

2 Answers2

3

Truth is that document.ready and bottom of document are pretty much the same thing, since by the end of document all controls are there. Personally I will still prefer document.ready since it's the way JQuery framework identifies document end (and ideally we should stick to framework's recommended ways) and secondly it will take care of anyone moving the code by mistake.

Beenish Khan
  • 1,571
  • 10
  • 18
  • 1
    +1 - It also communicates in no uncertain terms that the code doesn't run until the page loads. This is something we might not see right away of we're concentrating on solving a different problem. – jamesmortensen May 26 '12 at 06:38
2

When you write your code inline that way, assuming you load jQuery in the head, having the document onReady may not be necessary.

It starts to make a difference when your page code is loaded via an external JavaScript resource in the document (which may not be at the bottom). Reasons to do so are mainly so that the code can be cached by your browser and so reduces network overhead.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309