
코드스테이즈 41기 교육 내용을 정리하고 있습니다.
틀린 부분이 있으면 댓글로 알려주시면 감사하겠습니다.
일반적으로 CSS를 불러오기 위해 <link>요소를 <head>요소의 자식 요소로 하고, javascript를 불러오기 위해 <script>요소를 <body>요소 끝나기 직전에 위치시키는 이유가 무엇인가요?
link요소를 head요소에 자식요소로 넣어서 CSS를 불러오는 가장 큰 이유는 웹페이지가 로드되는 즉시 CSS가 적용되기 때문이다.
link요소가 body요소가 끝나기 전에 위치 할 경우, body와 body의 후손 요소들이 웹 페이지로 로드 된이후 CSS가 적용되기 때문에 웹 페이지에서 로드 되는 요소가 많거나, 인터넷 환경이 좋지 않을 경우 CSS가 적용되지 않은 웹 페이지가 사용자에게 보여지게 됩니다.
body요소가 끝나기 전에 script요소를 위치시켜 javascript를 불러오는 이유는 DOM의 사용 오류를 막기 위해서 이다.
예를 들어서 script가 head에 위치해있고, javascript는 Dom을 사용해 body안에 div요소를 불러온다고 가정하자.
다음의 경우 head에 있는 script가 먼저 실행이 되고 body요소 안에 div요소가 실행된다. 그렇게 되면 script는 body안의 div요소를 찾지 못하고 오류를 반환한다.
let div = document.createElement('div')
let main = document.querySelector('#main')
div.textContent = 'hello'
main.append(div)
다음과 같은 script.js 파일이 있다.
div요소는 red border를 주는 style.css파일이 있다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>html</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="main">
<div id="div">
안녕
</div>
</div>
<script src="test.js"></script>
</body>
</html>
다음 html을 실행하면 문오류 없이 main요소 마지막에 hello를 출력하는 div요소가 생긴다.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>html</title>
<link rel="stylesheet" href="style.css">
<script src="test.js"></script>
</head>
<body>
<div id="main">
<div id="div">
안녕
</div>
</div>
</body>
</html>
다음의 경우 script.js가 id가 main인 태그를 찾지 못하고 오류가 발생한다.

https://www.edureka.co/community/62788/generally-position-between-head-head-script-just-before-body
Why is it generally a good idea to position CSS link s between head head and JS script s just before body
Is there any exception exits if i do vice-versa. Does it a good practice to have js before css??
www.edureka.co
https://medium.com/geekculture/where-to-put-a-script-tag-into-head-or-body-end-b5b063058e0b
Where to put a script tag — into head or body end?
Let’s make simple tests to figure out what is the best place for a script tag.
medium.com
'프론트엔드 > Codestates' 카테고리의 다른 글
| [React] React SPA/ React Router (0) | 2022.10.04 |
|---|---|
| [React] JSX/ map을 이용한 반복/ Component (0) | 2022.10.04 |
| [Javascript] Node.js 모듈 (0) | 2022.09.27 |
| [Javascript] 비동기 (1) | 2022.09.26 |
| [Javascript] 프로토타입 체인 (0) | 2022.09.22 |