Rudy
Rudy

Reputation: 895

jQuery DOM Ready

In the following code snippet:

<form>
    <fieldset>
        <button id="indexGetStarted" class="button" type="submit">Get Started!</button>
    </fieldset>
</form>
<script type="text/javascript">

    $(document).ready(function() {

        $('#indexGetStarted').click(function() {
            $('form').submit();
            return false;
        });

    });

</script>

Is $(document).ready(function() { ... } necessary?

Upvotes: 1

Views: 6441

Answers (4)

David Hellsing
David Hellsing

Reputation: 108520

No, it's not needed. If you place scripts after the DOM elements in the source, the elements are naturally available. Some tests shows that this will speed up rendering, especially in IE.

You can bind stuff to the 'ready' event earlier in the markup and then run $.ready() before closing the body with the same effect.

Upvotes: 0

Tom Bartel
Tom Bartel

Reputation: 2258

Strictly speaking, it is always necessary if you access DOM elements in the enclosed code. $(document).ready() delays the execution of the code until the DOM tree is fully built, which is important, as you access the DOM tree via $('#indexGetStarted'). Practically, it will probably work anyway, but I would not recommend it.

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129832

Not absolutely, since you have declared your button (and then supposedly your form) before this script is being executed, it'll always be available. but removing that function would make your code dependent on where in the document the script block and the html elements are, in relation to one another.

Upvotes: 9

gnarf
gnarf

Reputation: 106392

Yes, It is required for writing clean code, but it has a shortcut:

$(function() { .... });
// is the same as
$(document).ready(function() { .... });

The behavior of manipulating DOM objects, attaching events, etc before the DOM Objects have fully loaded will be unpredictable, and often not work at all.

It might work if the elements are declared before the script portions load.

Upvotes: 2

Related Questions