script
작성 수정
-
defervsasyncdefer스크립트 실행 순서를 보장 + DOM이 완전히 준비된 후 실행되어야 하는 스크립트에 적합async순서와 상관없이 독립적으로 실행되는 스크립트에 적합
-
html에Javascript를 추가하는 방법headbodyhead+asynchead+defer
1. script in head
<head>
<script src="main.js" />
</head>
<!-- 많은 시간이 소요된다. -->
2. script at the end of body
<body>
<div></div>
<script src="main.js" />
</body>
<!-- DOM요소가 JS에 의존적이라면 정상적으로 페이지가 작동하기 까지 오래걸린다. -->
3. script async in head
<head>
<script async src="main.js" />
</head>
- async속성은 boolean type이기 때문에 선언만해도 true로 초기화된다.
- 장점:
script의 다운 속도를 줄일 수 있다. - 단점:
html이parsing되기 전에 JS가 동작하기 때문에,querySelector같은 DOM요소 조작이 정상 작동하지 않을 수 있다.
4. script defer in head
<head>
<script defer src="main.js" />
</head>
fetching,executing시간을 절약할 수 있다.- html이 parsing이 끝나고 작동하기 때문에 정상적으로 작동한다.
When multiple script is added
