user2580108
user2580108

Reputation:

Syntax difference in jQuery document ready

is there a difference in doing

$(document).ready(myFunction);

and

$(document).ready(myFunction());?

Upvotes: 0

Views: 73

Answers (1)

Scimonster
Scimonster

Reputation: 33409

Big difference - $(document).ready(myFunction()); will call the function immediately, and use the return value as the ready handler. $(document).ready(myFunction); will use myFunction as the handler.

Some clarification:

$(document).ready(myFunction); is the proper way to do it. This sets the function myFunction as the handler for the ready event - the function that will be executed when the event happens.

In 99% of cases, $(document).ready(myFunction()); is the wrong way to do it. What happens here is that myFunction is called immediately, not when the ready event occurs. If myFunction() returns a function, that returned function will be used as the event handler. However, this is a more advanced usage, and requires knowledge of closures and first-class functions.

Upvotes: 8

Related Questions