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?)

Community
  • 1
  • 1
Manuel Navarro
  • 1,789
  • 2
  • 16
  • 18
  • Refer to the API site when in doubt.. http://api.jquery.com/ready/ – Fabrício Matté Sep 26 '12 at 16:11
  • Next time, please do at least some research before posting a question. You'd know the answer by [googling](https://encrypted.google.com/search?q=site:stackoverflow.com+jquery+document+ready+vs+%24), or after [looking in the source code](https://github.com/jquery/jquery/blob/c3b1367f4c19abf12eadc1460a37dc34ae765e1b/src/core.js#L157). – Rob W Sep 26 '12 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... – Manuel Navarro Sep 26 '12 at 16:15

3 Answers3

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.

moonwave99
  • 21,957
  • 3
  • 43
  • 64
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.

Adil
  • 146,340
  • 25
  • 209
  • 204
-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).

Eduardo Costa
  • 1,974
  • 1
  • 16
  • 22