Both methods implement running a js after the HTML page is loaded

  • 2020-03-30 03:23:10
  • OfStack

Js method:
 
<script type="text/javascript"> 

window.onload=function(){ 

var userName="xiaoming"; 

alert(userName); 
} 

</script> 

The following is the jQuery method, and you need to refer to the jQuery file.
 
<script type="text/javascript"> 

$(document).ready(function(){ 

var userName="xiaoming"; 

alert(userName); 
}); 

</script> 

Or short for that
 
$(function(){ 
var userName="xiaoming"; 
alert(userName); 
}); 

When the dom is fully loaded, it can be executed (earlier than window.onload). You can appear multiple times on the same page.

PS: the main difference between the two

Window. Onload:

The window.onload event is triggered when a document is fully downloaded to the browser. This means that all elements on the page are operable by js, which means that all elements on the page will not be executed until they have been loaded. This is a great advantage for writing functional code, because you don't have to worry about the order of loads. ,

The $(document). Ready {} :

Is called when the DOM is fully in place and ready to use. While this also means that all elements are accessible to the script, it does not mean that all associated files have been downloaded. In other words, when the HMTL download is complete and parsed into the DOM tree, the code executes.

Here's an example:

Suppose you have a page that represents a gallery that might contain many large images that you can hide, display, or otherwise manipulate through jQuery. If we set up the interface with the onload page, then the user must wait until each image is downloaded before being able to use the page. Worse, if the behavior is slightly added to elements (such as links) that have default behavior, the user's interaction can lead to unexpected results. However, when we try setting $(document).ready(){}, the interface is ready for the correct behavior available earlier.

Using $(document).ready(){} is generally better than trying out the onload event handler, but it is important to be clear that because the supporting file may not be finished yet, attributes such as the height and width of the image may not be valid.

Note: placing js at the bottom of the page and applying defer="defer" can be problematic. Best to use the above function!

Related articles: