Using Self Calling Anonymous Functions and $(document).ready
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 use jQuery
anytime you wanted to work with jQuery. This can get quite ugly:
jQuery(function(){
jQuery('a', '#content').bind('click', function(){
if(jQuery(this).attr('href') == 'www.google.com')
{
alert("This link goes to Google");
jQuery(this).addClass('clicked'));
}
});
})
Remember, we can't use $
because that is a method from Prototype in the global scope.
But if you wrapped it inside of this..
(function($){
$(function(){
// your code here
});
})(jQuery);
The $
would actually reference the jQuery library inside while still referring to Prototype on the outside! This can help tidy up your code:
(function($){
$(function{}(
jQuery('a', '#content').bind('click', function(){
if(jQuery(this).attr('href') == 'www.google.com')
{
alert("This link goes to Google");
jQuery(this).addClass('clicked'));
}
});
));
})(jQuery);
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.
Self executing Anonymous functions in javascript
Self-executing anonymous functions and jQuery's ready
event handler have nothing to do with one another so no, it's not redundant.
Dollar sign before self declaring anonymous function in JavaScript?
The first uses jQuery to bind a function to the document.ready
event. The second declares and immediately executes a function.
Correct use of jQuery DOM ready and self invoking function
You're correct in saying that without DOM Ready, you might not be able to access some of the Page Elements. Although it depends on were you load your script. If you put it at the bottom before the closing body tag, you will not need the ready event to access elements.
(Sidenote: As with the DOM Ready Event Images won't be loaded at this time though. For this you can use $(window).load() for example).
Personally I like the first one most, I would however also put the Dom Ready Code in a seperate function. You actually don't need to call app.init() from the outside right after invoking the function, you can call it form inside. Like so:
var app = (function($){
// Initialisation Functions (Don't forget var)
var init = function () {
// init stuff
},
domInit = function () {
// DOM Ready stuff here
};
// Function calls
init();
$(function(){
domInit();
});
// if you want to call those functions
// some time later from outside of app,
// return them:
return {
init: init,
domInit: domInit
}
})(jQuery);
Self calling functions inside of $(document).ready(function(){ ... });
In difference lies in the order of execution:
jQuery(document).ready(function($) {
$(function () {
// inner handler
});
// outer handler
});
Code inside the inner ready
handler is executed after the code in the outer handler: http://jsfiddle.net/nmD8b/.
jQuery(document).ready(function($) {
(function () {
// do something
})();
// outer handler
});
Code inside the immediate function expression is executed right where the function is defined, i.e. before code following the expression: http://jsfiddle.net/nmD8b/.
If you want to scope variables, use the second way. The first way does not make a lot of sense, you should only register ready
event handlers when you actually need them. In this case, the DOM is already ready, because you bind the handler inside another ready handler.
If you don't want to scope variables, use neither of them. Just put all your code inside the outer handler.
How to use jQuery.ready with other anonymous self executing functions?
You can't.
The only way to communicate with a function outside your scope is to put an object somewhere in the global scope.
Instead, you should call $(document).ready()
inside the IIFE, so that it will be able to access local variables via closures.
Do self executing functions run at dom ready?
Nope. A self executing function runs when the Javascript engine finds it.
However, if you put all of you code at the end of your document before the closing </body>
tag (which is highly recommended), then you don't have to wait for DOM ready, as you're past that automatically.
If all you want is to scope your $
variable, and you don't want to move your code to the bottom of the page, you can use this:
jQuery(function($){
// The "$" variable is now scoped in here
// and will not be affected by any code
// overriding it outside of this function
});
Related Topics
What's the Best Way to Retry an Ajax Request on Failure Using Jquery
Is There a Good JavaScript Minifier
Migrating Angularjs to Angular 4,5 (With Demo)
What Happens When Using This.Setstate Multiple Times in React Component
Fade Background Image in and Out with Jquery
How to Submit a Form When the Return Key Is Pressed
How to Print a PDF from the Browser
Detect Browser Wrapped Lines via JavaScript
Show Loading Icon Until the Page Is Load
Get List of All Input Objects Using JavaScript, Without Accessing a Form Object
Send Post Data on Redirect with JavaScript/Jquery
How to Read from Chrome's Console in JavaScript
Console.Log Showing Only the Updated Version of the Object Printed
How to Handle the 'Onkeypress' Event in Reactjs
Value Was Evaluated Just Now with Console.Log on JavaScript Object
What's the Difference Between Putting Script in Head and Body
How to Use Any HTML5 Fanciness to Export Local Storage to Excel