开发者

jQuery DOM Ready

In the following code snippet:

<form&g开发者_StackOverflowt;
    <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?


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜