Javascript can only perform certain operations on DOM elements after they have been defined. This problem is described in detail in the article "Javascript Execution Sequence" //www.VeVB.COm/article/44577.htm.
jQuery uses document.ready to ensure that the code to be executed is executed after the DOM element is loaded. For example, in the article "jQuery Basics - How to Get Started", I used the following jQuery code:
Copy the code code as follows:
<!-- $(document).ready(function ()
{
alert("My first jQuery code!");
});
// -->
The meaning of this code is: when the Dom Tree is loaded, a warning message is displayed.
document.ready() is similar to the traditional method <body onload="load()">, except that the onload() method occurs after the page is loaded, including DOM elements and other page elements (such as images) loading,
Therefore, the execution speed of using the document.ready() method is faster than the onload() method.
Two final points to note (from jQuery documentation):
1. Make sure there is no registered function in the onload event of the <body> element, otherwise the $(document).ready() event may not be triggered. (
I tried to demonstrate this with the example below, but without success, so I guess this is just a possibility. )
Copy the code code as follows:
<html>
<head>
<title>My second jQuery</title>
<mce:script type="text/javascript" src="/js/jquery.js" mce_src="js/jquery.js"></mce:script>
<mce:script type="text/javascript">
<!-- //The following is the load function containing 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>"); }); // -->
</mce:script>
</head>
<body onload="load()">
<h2>jQuery simple example 2</h2>
<p>I would like to say: </p>
</body>
</html>
2. The $(document).ready() event can be used unlimited times in the same page. The registered functions will be executed in sequence (in the code).