What is the difference between (function () {}) (); and jQuery's $(document). Ready (function () {});

I originally thought that both of them were the same effect, so I replaced all the jQuery with native ones. Most of the code is fine, but one function has been reported wrong, so what"s the difference between these two pieces of code?

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

what"s the difference between these two? Why does some code work well and others fail?
how should I write it if I want to use the native one?

Oct.12,2021

1 is the anonymous function that executes immediately
2 is triggered after domcontentloaded


  1. the first piece of code is encapsulated anonymously and is generally used to encapsulate plug-ins or write your own business code. The advantage is that the variables inside will be sealed in the outermost function scope and will not pollute the environment
  2. .
  3. the ready standard of the old version of jQ is $(document). Ready (function () {}) (and several others are more or less the same). The abbreviation (jQ packaging) is $(function () {}) . After 3.0 +, the standard writing is $(function () {}) (of course, the original is also compatible). In addition, another way of writing is added, that is,

    .
    
    

    1.(function(){

    }) ();

    is a function that executes immediately, can be self-executed without a call, and can be thought of as a normal block of code. However, ordinary functions need to be called with a function name before they are executed, and normally they are not executed by themselves.

    2.$ (document) .ready (function () {

    });

    is a function of jq, which means that the document is executed after it has been loaded. Usually, if you use jq, you can write the logic code into this function.

Menu