Home >Web Front-end >JS Tutorial >JS implements code execution after document loading is completed_javascript skills
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>
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>
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.