0

Possible Duplicate:
What is the difference between these jQuery ready functions?
Are $(function(){}); and $(“document”).ready(function(){}); the same?
start javascript code with $(function, etc

Today, while reviewing some javascript code I found that some portions of code where written in a $(function() { }) section, and other part of code where inside a $(document).ready(function() { }) one. So my first reaction was: OK, What's the difference?

After a little of googling I found the next statement in the jQuery tutorial Getting Started with jQuery:

The following is a shortcut for the $(document).ready(callback) notation:

$(function() {
    // code to execute when the DOM is ready
});

Now, the question is: Is $(function() { }) an exact equivalent to $(document).ready(function() { })?

(And also a "less-global" indirect question will be: Is safe for me to put all the code in just one of the two sections?)

3
  • Refer to the API site when in doubt.. api.jquery.com/ready Sep 26, 2012 at 16:11
  • Next time, please do at least some research before posting a question. You'd know the answer by googling, or after looking in the source code.
    – Rob W
    Sep 26, 2012 at 16:13
  • Sorry, I swear that the duplicate question didn't show up when I search for the answer. This question should be closed for duplicated... Sep 26, 2012 at 16:15

3 Answers 3

5

Yes, $(function() { }) is a shorthand for $(document).ready(function() { }).

All three of the following syntaxes are equivalent:

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

From .ready() reference.

1

(function() { }) and $(document).ready(function() { }) could be used interchangeably and its upto us to choose the one we like. I feel $(document).ready(function() { }) mode readable and understandable when going through code.

-1

Yes, they are exactly the same and yes, it's safe to put both on the same block (assuming there's nothing relevant between them).

Not the answer you're looking for? Browse other questions tagged or ask your own question.