Are the end results of the following jQuery snippets identical?
Snippet 1:
$(function() { alert(\'test!\'); });
Yes:
$(document).ready(function() {
/* code */
});
…and:
$(function() {
/* code */
});
…are effectively the same, and the latter is commonly referred to as shorthand for the former.
If you're wondering why they produce the same outcome, it has to do with the jQuery constructor—the jQuery()
function, aliased as $()
—and its allowed inputs.
The constructor is documented at api.jquery.com/jquery/, and its two relevant options are outlined below.
jQuery( selector [, context ] )
Accepts a string containing a CSS selector which is then used to match a set of elements.
Returns a jQuery object.
This option above is how you're invoking the jQuery constructor when writing:
$(document).ready(function() { /* code */ });
The document
object is selected and used to construct a jQuery object. When the DOM is fully loaded, that jQuery object invokes the callback (the anonymous function) within ready().
jQuery( callback )
Binds a function to be executed when the DOM has finished loading.
Returns a jQuery object.
This option above is how you're invoking the jQuery constructor when writing:
$(function() { /* code */ });
The callback function (the anonymous function) is used to construct a jQuery object, and when the DOM is fully loaded, it is invoked.