Reputation: 29
what is the difference between the two jQuery function shown below?
(function($){console.log("Hello");})(jQuery);
$(function(){console.log("Hello");});
Upvotes: 1
Views: 157
Reputation: 74738
what is the difference between the two jQuery function shown below?
Your first code snippet:
(function($){console.log("Hello");})(jQuery);
This an anonymous self executing function which does not wait for dom to be loaded it just happens as soon as request gets in browser.
Another thing is you can see the $
in the params it just secures the $
alias for referencing the jQuery.
The code snippets you have you might don't see any difference but you can see the difference when you work on dom nodes. see the example below:
You can see an alert of undefined
because it does not wait for DOM to be loaded.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
(function($) {
alert($('#mybtn').val());
})(jQuery);
</script>
<input type='text' id='mybtn' value='123'>
Your second code snippet on the other hand is different. That is a shorter version of $(document).ready(fn)
:
$(function(){console.log("Hello");});
Whatever written in the doc ready block always runs when DOM gets ready. You can see the difference in the same code example as:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
(function($) {
$(function() { // this waits for dom to get ready.
alert($('#mybtn').val());
});
})(jQuery);
</script>
<input type='text' id='mybtn' value='123'>
Upvotes: 2
Reputation: 33218
The first one (function($){console.log("Hello");})(jQuery);
is just a self execute function.
The second one $(function(){console.log("Hello");});
is a shortcut to $(document).ready(function(){});
and execute when DOM is ready.
Upvotes: 1
Reputation: 101604
The first is simply a self-executing function specifying that $
is an alias to the global jQuery
. The latter is actually an alternative to binding to $(document).ready(function(){ ... });
.
// First variation (firing on DOM ready)
$(document).ready(function(){
console.log('Hello');
});
// Which the functional equivalent to:
$(function(){
console.log('Hello');
});
The first is how you'd usualy overcome $.noConflict
while retaining the $
shortcut.
$.noConflict();
(function($){
// $ is, within this scope, still a reference to jQuery
// despite $.noConflict
$('<p>').text('Hello').appendTo('body');
})(jQuery);
Upvotes: 2