0

Please let me know .What this below statment means in JS-

$(function () { /* Code */ });

Is this a anonymous function/ or a Jquery equivalent to document.ready?

Thank You,

3
  • in short its equivalent to document.ready Commented Nov 19, 2014 at 9:03
  • "Jquery equivalent to document.ready?" Yes. Passing an anonymous function to the jQuery function is a shortcut to $(document).ready() Commented Nov 19, 2014 at 9:04
  • Your code above is not legal JS. It appears to be missing a closing paren. Commented Nov 19, 2014 at 9:28

4 Answers 4

3

there is no diff between

$(function () { });

and

$(document).ready(function(){});

Both are use for wrapping when dom is ready.

actually $() is shorthand for $( document ).ready()

Sign up to request clarification or add additional context in comments.

Comments

1

Breaking it down:

$ is an alias of jQuery - the global function defined by the jQuery library.

This statement makes a call to the $ function:

$(/* args */)

This function accepts various different types of arguments, and behaves differently according to what argument(s) you pass it.

In the statement in question, an anonymous function is being passed as the single argument to the $ function: (note that a closing parenthesis is required to complete the statement originally given in the question):

$(function () { /* Code */ })

If passed a function, $ will add the function as an event handler for jQuery's [DOM] ready event. This means that the function will be queued up to be executed when the document has finished loading. If the document has already finished loading, the function will simply be executed immediately.

In this way, passing a function to $ acts as a shorthand version of:

$(document).ready(function() {
    /* code to execute on dom ready */
})

Comments

0

It's both an anonymous function (you created a function without giving it name) and a shorthand for the document ready event handler.

Note that you are also missing a closing bracket in your code, it should be

$(function () { /* Code */ });

Comments

0

$(function () { }); is executed as soon as the DOM is parsed and is invoked in order of appearance if there are multiple appearances. At this point the document is however not displayed, its just parsed.

and is the equivalent of $(document).ready(function () { });

The obvious benefit is that having your script tag before other elements on the page means that your script can interact with them even though they're not available at parse time. If you run your script before elements have been parsed and the document is not ready, they will not be available for interaction.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.