I just recently learned about self calling anonymous functions. Some snippets of code that I came across used the self calling function along with the $(document).ready. It seems redundant, or pointless, to use both.
Is there a case where you’d use
(function(){
$(document).ready();
})();
vs.
$(document).ready(function(){
(function(){})();
});
I figure that you’d either want the script to be executed right away or after the DOM loaded. I can’t see why you’d use both together.
Thanks.
There’s definitely a use case for the first example. If you have other JS libraries/scripts loaded on the same page, there’s no guarantee that they aren’t overwriting the
$variable. (This is very common when you have Prototype and jQuery on the same page).So if Prototype is using
$, you would need to usejQueryanytime you wanted to work with jQuery. This can get quite ugly:Remember, we can’t use
$because that is a method from Prototype in the global scope.But if you wrapped it inside of this..
The
$would actually reference the jQuery library inside while still referring to Prototype on the outside! This can help tidy up your code:This is a common pattern with jQuery extensions to ensure that they are always added to the jQuery object, but can be written using
$to keep the code tidy.