$ (Document). ready () in jquery
This article mainly summarizes the usage of $ (document). ready () in jquery in detail. If you need it, you can refer to it for help.
Window. onload = function () {alert ("welcome ");}
This method is used to automatically execute the js Code (function) after loading the page ).
$ (Document). ready (function () {...}) is used to replace window. onload;
Document. ready () is similar to the traditional method <body onload = "load ()">. The difference is that the onload () method occurs only after the page is loaded, this includes the loading of DOM elements and other page elements (example). Therefore, use document. the ready () method is faster than the onload () method.
Javascript can perform an operation on a DOM element only after it is defined. jQuery uses document. ready to ensure that the code to be executed is executed when the DOM element is loaded.
For example:
The Code is as follows:
<Script type = "text/javascript">
$ (Document). ready (function (){
Alert ("My first jQuery code! ");
});
</Script>
This Code indicates that a warning message is displayed after the Dom Tree is loaded. Document. ready () is similar to the traditional method <body onload = "load ()">. The difference is that the onload () method occurs only after the page is loaded, this includes the loading of DOM elements and other page elements (example). Therefore, use document. the ready () method is faster than the onload () method.
Note the following two points:
Make sure that the function is not registered in the onload event of the <body> element. Otherwise, the $ (document). ready () event may not be triggered. (
I tried to use the following example to demonstrate this situation, but it was not successful, so I think this is only possible .)
The Code is as follows:
<Html>
<Head>
<Title> My second jQuery </title>
<Script type = "text/javascript" src = "/js/jquery. js"> </script>
<Script type = "text/javascript">
// The following is the load function that contains the jquery registration function $
Function load (){
$ ("P"). append ("<B> Hello </B> ");
}
// The following is the jQuery code.
$ (Document). ready (function (){
$ ("P"). append ("My first jQuery code! ");
$ ("P"). append ("<B> Hello </B> ");
});
</Script>
</Head>
<Body onload = "load ()">
<H2> jQuery simple example 2
<P> I wowould like to say: </p>
</Body>
</Html>
You can use the $ (document). ready () event infinitely on the same page. The registered functions are executed sequentially.