Javascript 작성을 진행하고, 해당 코드가 브라우저에 보여지는 공간인 HTML에
적용하는 방식에 대해 살펴보고자 한다.
inline은 태그에 직접 자바스크립트를 기술하는 방식으로
태그에 연관된 스크립트가 분명하게 드러난다.
<!DOCTYPE html>
<html>
<body>
<input type="button"
onClick="alert('Hello world!')"
value="Hello wolrd" />
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<input type="button" id="hello" value="Hello world" />
<script type="text/javascript">
const hello = document.getElementById("hello");
hello.addEventListener("click", function () {
alert("Hello world!");
});
</script>
</body>
</html>
getElementById('hello')는 HTML에서 hello라는 Id 요소를 찾아, 이를 나타내는 element 객체를 반환한다.
hello.addEventListener('click', function)은 hello를 click 할때 function을 실행시켜 준다. button을 누르면 function이 실행되는 방식이다.
하지만 가독성이 떨어져, 간단한 코드가 아니라면 파일을 따로 만들어 불러오는 방식을 채택하는 것이 좋다. (CSS, JS)
<!DOCTYPE html>
<html>
<body>
<input type="button" id="hello" value="Hello world!" />
<script type="text/javascript" src="script.js" />
</body>
</html>
script 에서 외부 파일을 불러오는 방식을 적용했다.
const hello = document.getElementById('hello');
hello.addEventListener('click', function () {
alert('Hello world!')
});
이렇게 작업하면, 코드가 분리되어 가독성이 높아지고 수정이 용이하다,
하지만 html body부분을 전부 읽고 js파일을 불러오는 방식이어서 실행까지 시간이 걸리는 단점도 존재한다.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" defer src="script.js" />
</head>
<body>
<input type="button" id="hello" value="Hello world" />
</body>
</html>
defer 속성은 불리언으로 브라우저가 스크립트 문서 분석 이후에 실행해준다.