디지털 컨버전스/Java Script
[Javascript] window.onload
gimyeondong
2020. 4. 14. 10:51
1) 스크립트가 바디와 섞여 있으면 복잡함
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="btn">버튼</button>
<script>
document.getElementById("btn").onclick = function(){
alert("Pop!")
</script>
</body>
</html>
2) 스크립트를 헤드 부분으로 이동시 동작하지 않음
(순차적으로 실행되기 때문에 버튼이 없는데 버튼에 이벤트 줄수 없음)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
document.getElementById("btn").onclick = function(){
alert("Pop!")
}
</script>
</head>
<body>
<button id="btn">버튼</button>
</body>
</html>
3)
onload 이벤트 리스너를 활용
- 로드가 완료 되면 실행
- 코드의 위치는 가장 위에 있지만 실제 실행은 맨 마지막에 실행된다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
window.onload = function(){
document.getElementById("btn").onclick = function(){
alert("Pop!")
}
}
</script>
</head>
<body>
<button id="btn">버튼</button>
</body>
</html>
External 방식으로 구현도 가능
onload를 두번쓰면 덮어씌워짐