Do native functions execute in dom?

Before I heard about performing my own functions, I always did this:

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

Will the self-fulfillment function have the same effect? Will it work on dom ready?

 (function doSomething($) { // blah })(jQuery); 
+7
source share
5 answers

Nope. The self-emitting function is triggered when the Javascript engine finds this.

However, if you put all the code at the end of the document before the closing </body> (which is highly recommended ), then you do not need to wait for the DOM to be ready, since you passed it automatically.


If all you need is the area of โ€‹โ€‹your $ variable and you don't want to move your code at 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 }); 
+9
source

It will not, it will be launched as soon as the JavaScript file is executed.

+1
source

No, self-tuning javascript functions run right there.

If you want to create a DOM ready function, write the following:

 $(function() { // this will run on DOM ready }); 

Which is short for:

 $(document).ready(function() { }); 
0
source

No, the self-execution function starts immediately after you โ€œdeclareโ€ it in your code. Even if it is in an external .js file.

In your example, there is a chance that your function will execute and the jQuery value will be undefined . If you want your code to run in DOMReady, keep using

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

or

 $(function(){ doSomething(); }); 

or even

 window.onload = function(){ doSomething(); } 
0
source

$(document).ready(function() { ... }); it simply associates this function with the finished event of the document, therefore, as you said, when the document is loaded, the event is fired.

 (function($) { ... })(jQuery); 

is actually a Javascript construct, and all this part of the code passes the jQuery object to the ($) function as a parameter and runs the function, so inside this function $ always refers to the jQuery object. This can help resolve name conflicts, etc.

So, # 1 is executed when the document is loaded, and # 2 is launched immediately, with a jQuery object named $ as an abbreviation

 $(document).ready(function(){ ... }); or short $(function(){...}); 

This function is called when the DOM is ready, which means you can start asking for items, for example..ready () will use different methods in different browsers to make sure the DOM is really ready.

 (function(){ ... })(); 

This is nothing more than a function that activates itself as soon as possible when the browser interprets your ecma- / javascript. Therefore, it is very unlikely that you can successfully act on the DOM elements here.

jQuery document.ready and anonymous anonymous function

0
source

All Articles