TIL 01 - script async와 defer

hojung choi·2021년 5월 19일
0

js

목록 보기
2/17
post-thumbnail

script async와 defer

head + script

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="index.js"></script>
</head>

진행방식

  1. html 파일을 한 줄씩 읽으며 css와 병합하며 dom요소로 변환
  2. script태그를 마주치게 되면 읽는것을 멈추고 index.js를 다운받고 실행하게 된다
  3. 모든 스크립트 다운->실행까지 끝난 뒤 다시 html을 parsing하게 된다

단점
js파일이 크거나 인터넷 연결상태가 느릴 경우 속도가 느리다


body + script

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>content</div>
    <script src="index.js"></script>
</body>
</html>

진행방식

  1. html 파일을 한 줄씩 읽으며 css와 병합하며 dom요소로 변환
  2. body까지 parsing을 모두 한 후에 js를 다운도르 -> 실행

단점
만약에 웹사이트가 js에 의존적이라면 사용자가 의미있는 컨텐츠를 볼 수 없다.


head + asyn

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script asyn src="index.js"></script>
</head>

진행방식

  1. html 파일을 한 줄씩 읽으며 css와 병합하며 dom요소로 변환
  2. script태그를 마주치게 되면 js다운로드를 명령함
  3. 계속해서 parsing진행
  4. js다운이 다 되면 실행기 위해 parsing을 중단

** 병렬적 요소로 전체 페이지가 다운로드 되는 시간을 줄 일 수 있다.

단점
js가 먼저 다운이 되기 때문에 queryselector와 같이 정의되지 않은 js가 있을 수 있다. 먼저 다운되는 순서대로 js가 실행되는것이기 때문에 순서에 의존적인 js가 있을경우 오류가 일어나게 된다


👍🏻 head + defer

<head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script defer src="index.js"></script>
    </head>

진행방식

  1. html 파일을 한 줄씩 읽으며 css와 병합하며 dom요소로 변환
  2. script태그를 마주치게 되면 js다운로드를 명령함
  3. 계속해서 모든 parsing을 끝까지 진행
  4. 모든 parsing이 끝난 후 순서대로 js를 실행시킴

가장 BEST인 방법은 head+defer의 조합 ‼️
asyn는 전에 js를 공부하며 asyn / await로 공부한 적이 있어 반가웠다 ㅎㅎ
회사에서 새로운 플젝을 시작할때마다 혹은 새로운 api를 쓸때마다 매번 하는 import인데 오늘 asyn와 defer을 쓰는건 처음 알게 되었다 😿
내가 얼마나 우물안 개구리였는지 오늘 또 느끼며 ㅠㅠ...💪🏻

profile
🧚🏻‍♀️ Front-End Developer

0개의 댓글