How does:
(function($) {
/// code
})(jQuery)
differ from $(document).ready(function()
in jquery?
I know what the ready
function does. It awaits until the HTML is loaded before it starts. However, does (function($)
do the same?
How does:
(function($) {
/// code
})(jQuery)
differ from $(document).ready(function()
in jquery?
I know what the ready
function does. It awaits until the HTML is loaded before it starts. However, does (function($)
do the same?
I know what the ready function does. It awaits until the HTML is loaded before it starts. However, does
(function($) { ... })()
do the same?
No it does not. It executes immediately when (and whenever) control reaches that statement.
Try running
$(document).ready(function() { alert('happens second'); });
(function($) {
alert('happens first');
})(jQuery);
to see this first hand.
(function($) {
/// code
})(jQuery)
This is a self-executing anonymous function, it will execute the code inside the block as soon as the javascript interpreter reads it.
This is not to be confused with the following statement, which is equivalent to jQuery ready:
$(function() {
// code
});
$(document).ready(function() {
// code
});
These jQuery ready functions will only execute after the DOM has finished loading all elements (images can take a fairly long time on slow connections).
The first and last two are NOT equal, the self-executing function will always happen before the jQuery ready function, sometimes long before depending on how large the page is and how slow the user's connection is.
the "shorthand" for $(document).ready()
is simply $()
:
//both do the same thing
$(document).ready(function(){
//run when DOM is ready
});
$(function(){
//run when DOM is ready
});
However, your first code is NOT the same as .ready()
. What you have there is an immediately-invoked function expression (IIFE), or in layman's terms, "run this function immediately"
//both are the same
(function($) {
//run stuff here immediately!
})(jQuery) //arguments outside wrapping parenthesis
(function($) {
//run stuff here immediately!
}(jQuery)) //arguments inside wrapping parenthesis
This is just equal to something like this "function-and-call" but without the function name (an anonymous function) and the call:
function functionWithNoName($){
//"jQuery" in the call is "$" in here
}
functionWithNoName(jQuery)
this method is often used to protect code that uses $
for jQuery while other libraries are using the same $
function name, thus prevent conflicts. jQuery just uses $
for a shorthand alias to jQuery
(you would not want to type jQuery('selector')
all the time, $('selector')
is shorter)
(function($) {
//run jQuery using the "$" safely in here
}(jQuery))
//while some other libraries like mootools use "$" out here