Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do self executing functions run at dom ready?

Before I heard about self executing functions I always used to do this:

$(document).ready(function() {
   doSomething();
});

function doSomething()
{
   // blah
}

Would a self executing function have the same effect? will it run on dom ready?

(function doSomething($) {
   // blah
})(jQuery);
like image 360
Charlie Chaplin Avatar asked Aug 28 '11 18:08

Charlie Chaplin


2 Answers

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
});
like image 197
Joseph Silber Avatar answered Nov 05 '22 12:11

Joseph Silber


It won't, it will be ran as soon as the JavaScript file is executed.

like image 22
Alexander Gessler Avatar answered Nov 05 '22 12:11

Alexander Gessler