1

What's the different between these three events?

Which one loads before/after others?

   <body> 
        <script type='text/javascript'> 
            $(document).ready(function(){
                console.log('Document %s',+new Date());
            });
            $('body').ready(function(){
                console.log('Body %s',+new Date());
            });
            $(window).ready(function(){
                console.log('Window %s',+new Date());
            }); 
        </script>
        <div>hello world</div>
    </body>

Strange thing is that , they fires on the same order as I put them on code. For current example. document one fires first and windows one fires at the last.

p.s. I've read window.onload vs <body onload=""/> , window.onload vs document.onload and few others.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jashwant
  • 28,410
  • 16
  • 70
  • 105

1 Answers1

8

They are exactly the same, and actually the argument passed to $(...) doesn't matter.


From the jQuery documentation about .ready:

.ready( handler )

handler - A function to execute after the DOM is ready.

All three of the following syntaxes are equivalent:

  • $(document).ready(handler)
  • $().ready(handler) (this is not recommended)
  • $(handler)

The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.

As seen the argument (selector) to $() is explicitly said to be optional (when doing $(...).ready), because of this we can safely assume that it's irrelevant to the end result.

Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
  • 1
    Also from the documentation: "The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted." – MrOBrian Jul 17 '12 at 20:03
  • 1
    oh. I always thought `$(function() { ... });` is a shortcut for `$(document).ready(function(){....});` only. Thanks for verifying. I have read jQuery docs earlier but you explained it in the way I can understand – Jashwant Jul 17 '12 at 20:12
  • 1
    @Jashwant this might be helpful for the other part of your question ,the executing order http://stackoverflow.com/questions/1148241/jquery-is-it-bad-to-have-multiple-document-readyfunction – sabithpocker Jul 17 '12 at 20:16