본문 바로가기
프로그래밍 개발/JS 웹

Javascript 이벤트 타입 - 문서 로딩

by Jinseok Kim 2020. 11. 26.
반응형

 

문서 로딩

 

 

웹페이지를 프로그래밍적으로 제어하기 위해서는 웹페이지의 모든 요소에 대한 처리가 끝나야 한다. 이것을 알려주는 이벤트가 load, DOMContentLoaded이다.

 

 

 

 

<!DOCTYPE html>
<html>
    <head>
        <script>
        var t = document.getElementById('target');
        console.log(t);
        </script>
    </head>
    <body>
        <p id="target">jinseok</p>
    </body>
</html>

위의 코드의 실행결과는 null이다. 왜냐하면 스크립트 문서보다 아래쪽에 위치한 <p id="target">jinseok</p>가 로딩되기 전에 자바스크립트가 실행되었기 때문이다.

 

 

 

이를 해결하기 위한 방법은 아래와 같이 스크립트를 문서 끝에 위치시키는 것이 있지만 또 다른 방법은 load 이벤트 타입을 이용하는 것이다.

<!DOCTYPE html>
<html>
<head>
    <script>
        window.addEventListener('load', function(){
            var t = document.getElementById('target');
            console.log(t);
        })
    </script>
</head>
<body>
    <p id="target">jinseok</p>
</body>
</html>

 

 

 

 

그런데 load 이벤트는 문서내의 모든 리소스(이미지, 스크립트)의 다운로드가 끝난 후에 실행된다. 이것을 에플리케이션의 구동이 너무 지연되는 부작용을 초래할 수 있다.

 

 

 

하지만 DOMContentLoaded는 문서에서 스크립트 작업을 할 수 있을 때 실행되기 때문에 이미지 다운로드를 기다릴 필요가 없다.

<!DOCTYPE html>
<html>
    <head>
        <script>
            window.addEventListener('load', function(){
                console.log('load');
            })
            window.addEventListener('DOMContentLoaded', function(){
                console.log('DOMContentLoaded');
            })
        </script>
    </head>
    <body>
        <p id="target">jinseok</p>
    </body>
</html>

※ DOMContentLoaded 이벤트는 IE9을 포함한 모든 브라우저에서 지원하고 있다.

 

 

 

 

 

반응형

댓글