1. JS basic (acync vs defer)

Changmok LEE·2023년 1월 14일

1. js reference site

https://developer.mozilla.org/ko/

2. script tag position에 따른 효율성(acync vs defer)

  • head or body

    <!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>
        1) <script src="main.js"></script>
    </head>
    <body>
    	2) <script src="main.js"></script></body>
    </html>
    1. script 태그가 head에 위치 할 경우
      • parsing HTML > (blocked) > parsing HTML
        (blocked) == fetching js > executing js

    2. script 태그가 body에 위치 할 경우
      • parsing HTML > fetching js > executing js
  • head + acync

    <!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>
        <script async src="main.js"></script>
    </head>
    <body></body>
    </html>
    • head + acync
      - parsing HTML > (blocked) > parsing HTML
      (blocked) == executing js
      fetching js == parsing HTML과 병렬적으로 실행
  • head + defer

    <!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>
        <script defer src="main.js"></script>
    </head>
    <body></body>
    </html>
    • head + defer
      - parsing HTML > executing js
      fetching js == parsing HTML과 병렬적으로 실행
  • acync vs defer

    <!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>
        <script defer src="a.js"></script>
        <script defer src="b.js"></script>
        <script defer src="c.js"></script>
    </head>
    <body></body>
    </html>
    • head + defer is winner
      • parsing HTML > executing js a, b, c
        fetching js a, b, c == parsing HTML과 병렬적으로 실행

      • when parsingHTML is done, page is ready
      • js 파일 전부 다운 받은 후에 순서대로 js 실행
      • 정의한 순서 대로 js가 실행되기 때문에 예상한 대로 스크립트 실행 가능

3. use strict

  • use strict
    'use strict';

    js is very flexible
    flexible === dangerous

    use strict 사용해 오류 발견 할 수 있음

profile
이창목

0개의 댓글