Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

JavaScript는 body 영역에 위치할 수 있는데, 이경우 페이지가 읽혀지면서 실행이 된다. 만약 head 영역에 위치한다면 호출될때 실행이 된다.

예제

Where to Put the JavaScript

JavaScript는 브라우저가 페이지를 읽어 들일 때 즉시 실행을한다. 그러나 항상 이렇게 되길 원하는게 아니다. 때때로 개발자는 어떤 이벤트에 반응해서 JavaScript 코드가 실행되기를 원한다.

head 영역에 위치

스크립트를 head 여역에 두었다면, 스크립트는 호출하거나 혹은 이벤트가 발생했을 때 실행이 된다.
<html>
<head>
<script type="text/javascript">
function message()
{
    alert("This Alert box is sample box!!!");
}
</script>
</head>

<body onload="message()">
</body>
</html>

body 영역에 위치

body 영역에 위치할 경우 페이지가 로드될때 스크립트도 실행된다.
<html>
<head>
</head>

<body>
<script type="text/javascript">
function message()
{
    alert("This Alert box is sample box!!!");
}
</script>


</body>
</html>

head와 body 모두에 위치

자비스크립트는 어떤영역에 설치하건 또 몇개를 설치하건 별다른 제한이 없다.
<html>
<head>
<script type="text/javascript">
....
</script>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>

외부에 위치

동일한 자바스크립트 코드가 여러영역에 위치할 경우 코드를 외부에 두어서 읽어오도록 할 수 있다. 외부에 존재하는 자바스크립트파일은 일반적으로 .js확장자를 가지도록 한다.

외부에 저장되는 자바스크립트 파일은 <script> 태그를 포함하지 않는다.

<html>
<head>
<script type="text/javascript" src="counter.js"></script>
</head>
<body>
</body>
</html>