html에 css, 자바스크립트 연결하기

최민혁·2023년 10월 24일

TIL

목록 보기
5/12
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./css.css" />
    <script type="module" src="./1.js"></script>
  </head>

  <body>
    <header id="head" class="header">최고의 영화</header>
    <div class="searchbox">
      <label>영화 검색: </label
      ><input id="movieName" type="text" placeholder="무얼 찾으시나요?" />
      <button id="searchButton">검색</button>

      <button onclick="refresh()" id="refreshButton">새로고침</button>
    </div>
    <section class="cardlist"></section>
    <script src="1.js"></script>
  </body>
</html>

위 코드로 보면 css와 자바스크립트를 head 태그 안으로 넣으면 된다.

css는 링크 태그를 이용해 파일이 있는 경로를 지정 해주면 된다.
자바스크립트는 자체 태그를 이용해 css와 마찬가지로 파일이 있는 곳의 경로를 지정 해주면 된다.

스크립트 태그안에 있는 type=module은 뭘까?

module타입은 브라우저가 js파일을 늦게 읽도록 만들어준다. 이게 먼소리임?

브라우저에는 html를 읽어주는 파서와 js를 읽어주는 js엔진이 존재한다. 브라우저는 우선순위로 html을 먼저 읽는다. 그런데 이 과정에서 js태그가 있다면 html파싱을 잠시 멈추고 js태그를 우선적으로 읽기 시작한다. 만약 js파일에 123을 콘솔하는 값이 찍혀있다면 그 값이 먼저 찍히고 html으로 넘어간다는 말이다.

그러나 module 타입은 이 과정을 막아준다. module이 적혀 있으면 html이 모두 파싱되고나서야 js가 읽힌다. body태그에 123이 있다면 123이 보여지고나서 js엔진이 js파일의 123을 출력한다는 말이다.

사용자에게 좀 더 빠른 화면을 보여주고 싶다면 type = module을 사용하자.

profile
최민혁

0개의 댓글