简体   繁体   中英

What is the point of putting the $(document).ready function if the code is at the bottom?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM