Reputation: 195
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,
Upvotes: 0
Views: 94
Reputation: 1696
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 */
})
Upvotes: 1
Reputation: 1042
$(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.
Upvotes: 0
Reputation: 25352
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()
Upvotes: 3
Reputation: 20254
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 */ });
Upvotes: 0