티스토리 뷰
[본문은 양재동 코드랩에서 진행했던 자바스크립트 심화과정 DOM 2 수업 내용을 토대로 정리한 것입니다.]
onload & DOMContentLoaded
브라우저는 코드를 위에서 아래로 읽어내려가기 때문에 보통 헤더에 작성된 스크립트나 외부 링크된 스트립트에서
바디 안에 있는 DOM 객체를 찾거나 저장하면 error를 발생시킨다.
ex)
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
var el = document.getElementById("name");
console.log(el); //null
</script>
</head>
<body>
<div id="name"></div>
</body>
</html>
따라서 다음과 같이 바디 안 맨밑에 스크립트를 넣거나
ex)
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="name">
</div>
<script>
var el = document.getElementById("name");
console.log(el); //<div id="name"></div>
</script>
</body>
</html>
window.onload 를 이용하여 브라우저가 윈도우 모든 load를 완료한 후 스크립트 내용을 실행하도록
코드를 작성하게 된다. (window.onload는 하나의 onload만 존재해야함으로 마지막 load가 실행된다.)
ex)
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
window.onload = function(){
var el = document.getElementById("name");
console.log(el); // <div id="name"> </div>
};
</script>
</head>
<body>
<div id="name">
</div>
</body>
</html>
또는
window.addEventListener("load",function(){
var el = document.getElementById("name");
console.log(el); //<div id="name></div>
});
-addEventListener 의 설명 및 호환성
[참조] https://developer.mozilla.org/ko/docs/Web/API/EventTarget/addEventListener
DOMContentLoaded
여기서 window.onload의 시점은 모든 문서 및 이미지까지 로드된 후를 의미하기 때문에
이미지를 컨트롤하지 않을 시에는 document가 모든 로드된 시점에 스크립트를 적용하는 것이 좋다.
아래 코드는 그 시점을 의미 한다.
ex)
document.addEventListener("DOMContentLoaded",function(){
var el = document.getElementById("name");
console.log(el);
});
하지만 DOMContentLoaded는 IE9 이상에서만 가능하다.
-DOMContentLoaded 설명 및 호환성
[참조] https://developer.mozilla.org/ko/docs/Web/Events/DOMContentLoaded
jQuery 에서는 window.onload 다음과 같이,
$(window).load(function(){
});
DOMContentLoaded 를 다음과 같이 사용한다.
$(document).ready(function(){
});
'javascript' 카테고리의 다른 글
ajaxForm&ajaxSubmit (0) | 2017.12.30 |
---|---|
참조타입외 (0) | 2017.03.13 |
- Total
- Today
- Yesterday
- 오라클정규식
- 오라클시스디비에스접속
- jsp
- 오라클
- orale
- 오라클시스템계정암호
- spring webpack 설정
- 오라클시스템계정잠김
- srpring
- spring5
- veujs
- webpack
- 오라클정규식함수REGEXP
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |