-1

What is the difference between (function(){})(); and $(document).ready(function ())

First: (function(){})();
Second: $(document).ready(function ())

I have a question about it.
if I use it in the first option, there is an error when I click it. The Error is that it does not work and there is no error. but if I use the second one, there is no error. It is not working. what is the difference between to two ?

SUAT SUPHI
  • 417
  • 1
  • 4
  • 14

1 Answers1

3

This will execute immediatly:

(function(){
    console.log("Called immediately invoked function expression");
})();

Where as, the function passed to jQueries $.ready() function will execute when the document can be safely manipulated:

$(document).ready(function () {
    console.log("The document is safe to be interacted with");
});

The reason the first method causes errors is likely because the HTML document is not ready for interaction at the time that your function is called (ie immednaitly).

The second approach will however ensure that (in most cases), any scripts, HTML, or other resources (which the JavaScript defined in that function might depend on) are loaded and present before that function is invoked.

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65