The difference between js entry function and jQuery entry function

The window.onload event of JS must wait until all content and files such as external images are loaded before it is executed.

The JQuery entry function is executed after all tags are loaded.

Next, an explanation of the implementation of the JQuery entry function is introduced through a coverage problem of JS.

The window.onload function of the entry function of JS has a coverage problem. When two window.onload functions appear in the document, the latter will overwrite the former, resulting in the function not being realized. But JQuery does not have such a problem. The important reason is that the JQuery entry function is just a call to the encapsulated method, but the parameters passed are different.

 

Finally, let's talk about the implementation of the JQuery entry function ($(document).ready();).

 

First, we create a function variable called $ in the script tag, and then call it later. Now it doesn't have any effect because this call is just an empty object with no arguments. If we want to continue calling after $(), we need to do a few more things. Let's see if there is a ready method in the JQuery entry function, then we can create an object's property called ready, and then point ready to an anonymous function, and now we can call it through $().ready().

Test it with a specific function:

Next, the JQuery entry function can pass a function (passed in as a variable), that is, $().ready(function(){}), and then receive it with a formal parameter (func) variable, then strictly execute the received method, Just call (func()) once.

 

Let's take a look at the document parameter in front of the JQuery entry function, that is, $(document).ready(function(){}), which is exactly the same as the JQuery entry function. Also need to receive with a variable. Finally, just check whether the onload event has (or has been assigned) in the ready function:

(1) Yes (assigned), receive an old function, reassign the onload event, and then call the new function first, and then call the old function, so that there will be no coverage problem, both of them are implemented. .

(2) No, assign an onload event directly.

 

Finally, let's test it. Since document has no onload event, we can try it with window.

This avoids the problem of function overwriting.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325015010&siteId=291194637