window.onload() 方法用于在网页加载完毕后立刻执行的操作,即当 HTML 文档加载完毕后,立刻执行某个方法。
window.onload() 通常用于 <body> 元素,在页面完全载入后(包括图片、css文件等等)执行脚本代码。

1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset=" utf-8">
5 <title>测试</title>
6 <style type="text/css">
7 #bg{
8 width:100px;
9 height:100px;
10 background:blue;
11 }
12 </style>
13 </head>
14 <body>
15 <div id="bg"></div>
16 </body>
17 </html>
18 <script type="text/javascript">
19 window.onload=init();
20 init(){
21 alert("DOM加载完毕");
22 }
23 </script>
View Code
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<title>测试</title>
<style type="text/css">
#bg{
width:100px;
height:100px;
background:blue;
}
</style>
</head>
<body>
<div id="bg"></div>
</body>
</html>
<script type="text/javascript">
window.onload=init();
init(){
alert("DOM加载完毕");
}
</script>