본문 바로가기
Develop/JAVASCRIPT

자바스크립트 기초 - 스크립트 선언(defer, 상대 경로, 절대 경로, 루트 경로), 로그 출력(console.log)

by 걸어다니는 종합병원 2022. 11. 8.
반응형

스크립트 선언

script 태그 위치는 어느 곳이든 상관 없음.

head 태그 안이나, body 태그 안에도 사용 가능.

세미콜론(;)은 문장의 끝을 나타냄. 세미콜론을 생략해도 줄바꿈만 넣어주면 에러 없이 동작

<!doctype html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="style.css"/>
  <script>
    alert('안녕하세요!');
  </script>
</head>
<body></body>
</html>

<!doctype html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="style.css"/>
  <!-- main.js 불러오기 -->
  <script src="main.js" defer></script>
</head>
<body></body>
</html>

main.js

alert('반가워요!');

 

실행화면


 

<script> 태그의 defer 속성은 페이지가 모두 로드된 후에 해당 외부 스크립트가 실행됨을 명시.

defer 속성은 불리언(boolean) 속성으로 명시하지 않으면 false 값을 가지게 되고, 명시하면 true 값을 가짐.

defer  속성은 <script> 요소가 외부 스크립트를 참조하는 경우에만 사용할 수 있으므로, src 속성이 명시된 경우에만 사용할 수 있다.

 

script를 가져오는 방법

상대 경로

<script src="./script/main.js"></script>

루트 경로

<script src="/project/script/main.js"></script>

절대 경로

<script src="https://test.com/script/main.js"></script>

로그 - 콘솔에 값 표시

console.log(값1, 값2, ....) 

<!doctype html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="style.css"/>
  <script>
    const a = 10;
	const b = 20;
	const sum = a + b;
	console.log(sum); // 결과값: 30
  </script>
</head>
<body></body>
</html>

console.log()는 콤마(,)를 사용하여 하나 이상의 파라미터 전달이 가능.

console.log(100 + 300); // 덧셈 	: 400
console.log(300 - 120); // 뺄셈 	: 180
console.log(100 * 2);	// 곱셈		: 200
console.log(400 / 5);	// 나눗셈 	: 80
console.log(404 % 5);	// 나머지 	: 4
console.log(2 ** 3);	// 제곱 	: 8

반응형

댓글