window.onload 함수는 DOM tree가 완성된 뒤에 수행할 명령들에 대해서 적용하는 부분을 말한다.
<script>태그가 <body>의 마지막에 들어갈 경우에는 상관이 없지만 문서의 <head>라거나 특정 엘리먼트 앞에서 수행될 경우에는 아직 완성되지 않은 DOM tree에 대해서 명령을 수행하는 것이 불가능하게 된다. 이 때 이 함수를 이용하게 되면 어디에서 <script>명령을 내리던 간에 DOM tree가 완성 된 뒤에 수행하기 때문에 오류를 방지할 수 있다.
예)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>J031</title>
<style>
div, h1{
border: 1px solid red;
padding: 20px;
margin: 5px;
}
</style>
<script>
"use strict";
console.log('1111111');
window.onload = function(){
console.log('window.onload()....');
var h01 = document.getElementById('h01');
h01.addEventListener('click', function(event){
console.log('h01 select1');
};
});
(function(){
console.log('when called');
})();
console.log('2222222');
</script>
</head>
<body>
<script>alert('333333333');</script>
<h1>onload : DOM 트리 생성 -> 화면 출력 -> onload() 호출</h1>
<div id='d1'>
<div id='d11'><h1 id='h01'>d11</h1></div>
<div id='d12'><h1 id='h02'>d12</h1></div>
</div>
<script>alert('44444444');</script>
<div id='d2'>
<div id='d21'><h1 id='h03'>d21</h1></div>
<div id='d22'><h1 id='h04' onclick='console.log("html onclick")'>d22</h1></div>
</div>
<script>alert('5555555555555');</script>
</body>
</html>
댓글 없음:
댓글 쓰기