Home > Web Front-end > JS Tutorial > JS implements code execution after document loading is completed_javascript skills

JS implements code execution after document loading is completed_javascript skills

WBOY
Release: 2016-05-16 15:50:58
Original
1255 people have browsed it

When performing certain operations, you need to wait until the document is completely loaded before executing, otherwise unexpected situations may occur. Let’s take a look at a code example first:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<title>脚本之家</title>
<style type="text/css"> 
div{ 
 width:200px; 
 height:200px; 
} 
</style> 
<script type="text/javascript"> 
document.getElementById("mytest").style.backgroundColor="#639"; 
</script> 
</head> 
<body> 
<div id="mytest"></div> 
</body> 
</html>

Copy after login

The original intention of the above code is to set the background color of the div to #639, but it does not achieve the effect we expected. This is because the code is executed sequentially when the document is loaded. When the js code to set the background color is executed, , has not been loaded into the specified div, so the js statement did not obtain the object at all. The code is modified as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<title>脚本之家</title>
<style type="text/css"> 
div{ 
 width:200px; 
 height:200px; 
} 
</style> 
<script type="text/javascript"> 
window.onload=function(){ 
 document.getElementById("mytest").style.backgroundColor="#639"; 
} 
</script> 
</head> 
<body> 
<div id="mytest"></div> 
</body> 
</html>

Copy after login

The above code achieves the expected effect because the code is placed in a function, and this function is used as the event handler for the window.onload event. The condition for triggering the window.onload event is that the current document is completely loaded. When this event is triggered, its event processing function will be executed. In this way, because all documents have been loaded, there will be no situation where the js statement cannot obtain the object. .

The above is the entire content of this article, I hope you all like it.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template