Explain the difference between document.ready and window.onload

  • 2020-03-30 00:57:45
  • OfStack

Javascript can only perform certain operations on DOM elements after they have been defined, which is covered in the article "Javascript execution order" (link: #).

JQuery USES document.ready to ensure that the code to be executed is executed when the DOM element is loaded. For example, in "jQuery basics - how to get started, "I used the following jQuery code:


<!--   $(document).ready(function ()
         {   
          alert(" My first one jQuery code !");   
         });   
// -->

When the Dom Tree is loaded, a warning message is displayed.

Document.ready () and traditional methods < The body onload = "load ()" > Similarly, the onload() method does not occur until the page is loaded, which includes DOM elements and other page elements (such as images),

Therefore, the document.ready() method executes faster than the onload() method.

Two final points to note (from the jQuery documentation) :

1. Make sure you are in the Body> There is no registered function in the onload event of the element, otherwise the $(document).ready() event might not be triggered. (
I tried to demonstrate this with the following example, but it didn't work, so I think it's just possible.


<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">
<!-- //Here's the function load with the jquery registry function $& NBSP;  
function load(){  $("p").append("<b>Hello</b>"); }   
//Here's the jQuery code & NBSP;  
$(document).ready(function () 
{ $("p").append(" My first one jQuery code !"
);  
$("p").append("<b>Hello</b>");  });  // -->
</mce:script> 
</head>  
<body onload="load()">  
<h2>jQuery  A simple example 2</h2>  
<p>I would like to say: </p>  
</body> 
</html>  

2. The $(document).ready() event can be used an unlimited number of times on the same page. The registered functions are executed in sequence.


Related articles: