Take the 2-minute tour ×

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:

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

<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>
alert("In Page");


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

    $( "#accordion" ).accordion();

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

share|improve this question
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?" –  le dorfier May 26 '12 at 3:42
related (but not a dup IMO) stackoverflow.com/questions/8717401/… –  ajax333221 May 26 '12 at 5:55
@ledorfier - I almost fell out of my chair when I read that ;) That's hilarious. –  jmort253 May 26 '12 at 6:35
add comment

2 Answers

up vote 2 down vote accepted

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.

share|improve this answer
+1 sticking with framework recommendations! –  jasonflaherty May 26 '12 at 4:06
+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. –  jmort253 May 26 '12 at 6:38
add comment

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.

share|improve this answer
add comment

Your Answer


