프로그래밍/자바스크립트

생활코딩 Javascript 정리 - 자바스크립트 개념 및 HTML에서 자바스크립트 로드하기

가카리 2017. 6. 17. 14:35
반응형
1. 웹브라우저와 Javascript

Javascript

여기서 onclick 부분에서 클릭이 되면 클래스이름을 dark로 하라는 의미이다.
클릭 후 결과

2. HTML에서 JAVA Script 로드하기

1) inline 방법
inline 방식은 태그에 직접 자바스크립트를 기술하는 방식이다. 장점은 태그에 연관된 스크립트가 분명하게 드러난다는 점이다. 하지만 정보와 제어가 섞여 있기 때문에 정보로서의 가치가 떨어진다.
ex_1.html
<!DOCTYPE html>
<html>
<body>
    <input type="button" onclick="alert('Hello world')" value="Hello world" />
</body>
</html>
onclick은 HTML 문법 alert는 자바스크립트 문법임

2) script 태그 방법
ex_2.html
<!DOCTYPE html>
<html>
<body>
    <input type="button" id="hw" value="Hello world" />
    <script type="text/javascript">
        var hw = document.getElementById('hw');
        hw.addEventListener('click', function(){
            alert('Hello world');
        })
    </script>
</body>
</html>

3) 외부 파일로 분리
js를 별도의 파일로 분리할 수도 있다. 장점은 보다 엄격하게 정보와 제어를 분리할 수 있다. 하나의 js 파일을 여러 웹페이지에서 로드함으로서 js의 재활용성을 높일 수 있다. 캐쉬를 통해서 속도의 향상, 전송량의 경량화를 도모할 수 있다.
ex_3.html
<!DOCTYPE html>
<html>
<body>
    <input type="button" id="hw" value="Hello world" />
    <script type="text/javascript" src="./load/script.js"></script>
</body>
</html>
script.js
<!DOCTYPE html>
<html>
<body>
    <input type="button" id="hw" value="Hello world" />
    <script type="text/javascript" src="./load/script.js"></script>
</body>
</html>

4) Script 파일의 위치



출처 : 생활코딩(https://www.opentutorials.org/)


반응형