I understand that the following is shorthand for $( document ).ready()
:
$(function() {
console.log( "ready!" );
});
I also understand what an anonymous JS function is, but does jQuery does anything special when it's called using one. I.e.:
(function() {
console.log( "ready!" );
})($);
Is the latter just a normal anonymous JS function that uses jQuery (ie. it will NOT be considered shorthand for $(document).ready()
and so will execute immediately)?
I feel this MUST have been asked before, but I can't find it if it has.
The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.
So a jQuery function, which is prefixed with the $ or the word jQuery generally is called from within that method. $(document). ready(function() { // Assign all list items on the page to be the color red.
Use the callback function parameter.
This extend() Method in jQuery is used to merge the contents of two or more objects together into the first object. Parameters: The extend() method accepts four parameter that is mentioned above and described below: deep: This parameter is the merge becomes recursive . target: This parameter is the object to extend.
As you mentioned, the former is indeed a shorthand for $(document).ready()
.
As for the latter, this is just an Immediately Invoked Function Expression.
(function ($) {
console.log('ready');
})(jQuery);
This function is simply an anonymous function which receives a parameter named $
. The function is immediately invoked with some value (in this case jQuery
) as the parameter.
IIFEs can also be used to isolate scopes and to avoid global variables in web applications which contain multiple JavaScript files. In this case a parameterless IIFE could be used:
(function () {
// x is only accessible within this IIFE
var x;
// do something...
})();
For more information regarding Immediately Invoked Function Expression, see this question: What is the purpose of a self executing function in javascript?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With