Yesterday when I was writing a web page special effect, I always got an error. I didn’t know the reason until today through an example.
I always thought that using JavaScript's document.onLoad to specify a function is the same as adding onLoad to the Body tag. However, through today's example, I found that document.onLoad is not triggered when the page is loaded.
The sample code is as follows: (Test environment Win2003 + IE7)
1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2<html>
3<head>
4<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
5<title>Untitled Document</title>
6<script language="JavaScript">
7function mytest(){
8 alert(document.getElementById("my2"));
9}
10document.onLoad = mytest();
11</script>
12</head>
13
14<body>
15<p id="my2">Test content</p>
16</body>
17</html>
When opening the htm file in the example, a prompt dialog box pops up when the page is not fully displayed, that is, the screen is white. It means that mytest is called when the page is not completed.
Comment out the sentence document.onLoad, and then modify the body tag to
<body onLoad="mytest()">
Reopen the page. Mytest is called only after the page is loaded. I don’t know why, haha.