Skip to content

HTML5 치트시트

새로운 시맨틱 요소와 API를 갖춘 HTML의 5차 개정판입니다.

01

시맨틱 요소

문서 구조

HTML5는 브라우저와 개발자 모두에게 의미를 전달하는 시맨틱 요소를 도입했습니다. header, nav, main, article, aside, footer가 문서 구조를 정의합니다. DOCTYPE html이 표준 모드를 트리거하고, lang이 접근성과 SEO를 개선하며, 올바른 인코딩에는 charset UTF-8이 필요합니다.

html5
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Page Title</title>
</head>
<body>
  <header>Header content</header>
  <nav>Navigation</nav>
  <main>
    <article>Article content</article>
    <aside>Sidebar</aside>
  </main>
  <footer>Footer</footer>
</body>
</html>

Header & Footer

header는 소개 콘텐츠(로고, 제목, 검색 폼)를 나타내며 여러 번 나타날 수 있습니다. footer는 저작권, 링크, 연락처 같은 마무리 콘텐츠를 담습니다. 둘 다 페이지 수준뿐 아니라 article이나 section 같은 섹셔닝 요소 안에서도 사용할 수 있습니다.

html5
<header>
  <h1>Site Title</h1>
  <p>Tagline</p>
</header>

<footer>
  <nav>
    <a href="/about">About</a>
    <a href="/contact">Contact</a>
  </nav>
  <small>&copy; 2024 Example</small>
</footer>

내비게이션 요소

nav는 주요 내비게이션 블록을 위한 것입니다. 모든 링크 목록이 nav를 필요로 하는 것은 아닙니다 — 사이트 내비게이션에서 중요한 그룹만 해당됩니다. 여러 nav 요소를 구분하려면 aria-label을 쓰세요(예: 메인 vs 브레드크럼). aria-current는 현재 페이지를 나타냅니다.

html5
<nav aria-label="Main navigation">
  <ul>
    <li><a href="/" aria-current="page">Home</a></li>
    <li><a href="/blog">Blog</a></li>
    <li><a href="/about">About</a></li>
  </ul>
</nav>

<nav aria-label="Breadcrumb">
  <ol>
    <li><a href="/">Home</a></li>
    <li><a href="/blog">Blog</a></li>
    <li aria-current="page">Post</li>
  </ol>
</nav>

Main & Article

main은 페이지의 주요 콘텐츠를 감싸며 페이지당 한 번만 나타나야 합니다('main' ARIA 랜드마크에 매핑). article은 독립적인 구성입니다 — 블로그 글, 뉴스 기사, 위젯 — 재사용 가능합니다. section은 주제가 관련된 콘텐츠를 묶으며 항상 제목을 동반합니다.

html5
<body>
  <header>Site header</header>
  <main>
    <article>
      <h1>Blog Post Title</h1>
      <p>Body content...</p>
      <section>
        <h2>Subsection</h2>
        <p>More content</p>
      </section>
    </article>
  </main>
</body>

Section & Aside

section은 관련 콘텐츠를 묶으며 항상 제목을 포함해야 합니다. aside는 본문과 접선적으로 관련된 콘텐츠 — 사이드바, 풀 인용, 광고 — 를 나타냅니다. 둘 다 문서 아웃라인을 개선합니다. 섹션에 접근 가능한 이름을 주려면 aria-labelledby를 쓰세요.

html5
<section aria-labelledby="features-heading">
  <h2 id="features-heading">Features</h2>
  <p>Feature description</p>
</section>

<aside aria-label="Related links">
  <h2>Related</h2>
  <ul>
    <li><a href="/post-2">Next post</a></li>
  </ul>
</aside>

Figure & Figcaption

figure는 본문 흐름에서 참조되는 콘텐츠(이미지, 코드 목록, 인용)를 묶으며 figcaption이 캡션을 제공합니다. figcaption은 첫 또는 마지막 자식이어야 합니다. figure는 이미지에 국한되지 않습니다 — 코드 스니펫이나 blockquote 같은 독립적 콘텐츠에도 쓰입니다.

html5
<figure>
  <img src="chart.png" alt="Sales chart showing growth">
  <figcaption>Figure 1: Quarterly sales growth in 2024.</figcaption>
</figure>

<figure>
  <blockquote>
    <p>The best way to predict the future is to invent it.</p>
  </blockquote>
  <figcaption>— Alan Kay</figcaption>
</figure>
02

폼 개선

새 입력 타입

HTML5는 email, url, tel, date, time, color, range, number, month, week, datetime-local 같은 input 타입을 추가했습니다. 브라우저가 네이티브 검증과 전용 UI(데이트 피커, 컬러 피커)를 제공합니다. type=email/url은 폼 제출 시 자동 형식 검증을 트리거합니다.

html5
<form>
  <label>Email: <input type="email" required></label>
  <label>URL: <input type="url"></label>
  <label>Phone: <input type="tel"></label>
  <label>Date: <input type="date"></label>
  <label>Time: <input type="time"></label>
  <label>Color: <input type="color"></label>
  <label>Range: <input type="range" min="0" max="100"></label>
  <label>Number: <input type="number" min="0" step="0.01"></label>
  <button>Submit</button>
</form>

Datalist 자동완성

datalist는 list 속성을 통해 input에 자동완성 제안을 제공합니다. select와 달리 사용자가 자유 형식 텍스트를 입력하거나 제안을 고를 수 있습니다. 각 option의 value가 제안이 됩니다. datalist는 지원하지 않는 브라우저에서 일반 텍스트 입력으로 우아하게 저하됩니다.

html5
<label>
  Choose a browser:
  <input list="browsers" name="browser">
</label>
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Safari">
  <option value="Edge">
</datalist>

Output 요소

output은 계산이나 사용자 액션의 결과를 나타냅니다. JS로 접근 가능한 value 프로퍼티와 기여한 input을 참조하는 for 속성을 갖습니다. 폼 연계 요소이므로 값이 폼과 함께 제출됩니다. 실시간 계산기에 좋습니다.

html5
<form oninput="result.value = (+a.value + +b.value)">
  <input type="number" name="a" value="0">
  +
  <input type="number" name="b" value="0">
  =
  <output name="result" for="a b">0</output>
</form>

Progress & Meter

progress는 작업 완료를 보여줍니다(value/max); value를 생략하면 미정 상태입니다. meter는 알려진 범위 안의 스칼라 측정을 표시하며, low/high/optimum 임계값이 색에 영향을 줍니다. meter는 읽기 전용이며 진행 표시용이 아닙니다.

html5
<label>Uploading:
  <progress value="70" max="100">70%</progress>
</label>

<label>Disk usage:
  <meter value="0.6" min="0" max="1" low="0.4" high="0.8" optimum="0.2">
    60%
  </meter>
</label>

<!-- Indeterminate progress -->
<progress>Processing...</progress>

Form 속성 & Fieldset

form 속성은 id로 input, fieldset, button을 폼에 연결합니다 — 요소가 폼 안에 중첩되지 않았어도 됩니다. fieldset은 관련 컨트롤을 묶고 legend가 캡션을 제공합니다. fieldset의 disabled 속성은 포함된 모든 컨트롤을 한 번에 비활성화합니다.

html5
<form id="myForm" action="/submit" method="post"></form>

<!-- Input outside the form, but associated via form attribute -->
<label>
  Name:
  <input type="text" name="name" form="myForm" required>
</label>

<fieldset form="myForm" disabled>
  <legend>Shipping Options</legend>
  <label><input type="radio" name="ship" value="standard"> Standard</label>
  <label><input type="radio" name="ship" value="express"> Express</label>
</fieldset>

<button type="submit" form="myForm">Submit</button>

Placeholder & Autofocus

placeholder는 input 안에 힌트를 보여주고 포커스 시 사라집니다 — label의 대체가 아닙니다. autofocus는 페이지 로드 시 요소에 포커스를 줍니다(아껴 쓰고 페이지당 하나). autocomplete는 브라우저가 과거 값을 기억할지 제어합니다. title은 툴팁을 제공하지만 접근 가능한 라벨을 대체해서는 안 됩니다.

html5
<form>
  <label>
    Search:
    <input type="search" name="q"
           placeholder="Type to search..."
           autofocus
           autocomplete="off">
  </label>
  <label>
    Hint text:
    <input type="text" name="hint" title="Helpful tooltip">
  </label>
  <button type="submit">Go</button>
</form>
03

폼 검증

required 속성

불리언 required 속성은 필드를 필수로 표시합니다; 비어 있으면 브라우저가 제출을 차단하고 오류 말풍선을 보여줍니다. 모든 텍스트, 숫자, 체크박스, 라디오, 파일, select 컨트롤에 동작합니다. 시각적 피드백으로 :invalid와 :valid CSS 의사 클래스와 짝지으세요.

html5
<form>
  <label>
    Email (required):
    <input type="email" name="email" required>
  </label>
  <label>
    Optional phone:
    <input type="tel" name="phone">
  </label>
  <button>Submit</button>
</form>

pattern 검증

pattern은 값이 맞아야 하는 JavaScript 정규식(슬래시 없음)을 받습니다. ^와 $로 고정하는 것이 권장됩니다. title 속성이 실패 시 사용자에게 힌트를 줍니다. pattern은 type=email/url에 암시적으로 고정되지만 텍스트 계열 input에는 명시적입니다.

html5
<form>
  <label>
    Product code:
    <input type="text" name="code"
           pattern="[A-Z]{3}-\d{4}"
           title="Three letters, hyphen, four digits (e.g., ABC-1234)"
           required>
  </label>
  <label>
    Hex color:
    <input type="text" name="color" pattern="^#[0-9A-Fa-f]{6}$">
  </label>
  <button>Submit</button>
</form>

Min, Max & Step

min과 max가 숫자/날짜 input의 하한과 상한을 정의합니다. step이 증분을 지정하며 값은 min + n*step이어야 합니다. step='any'는 임의의 소수를 허용합니다. 브라우저는 제출 시 범위 밖 값을 거부하고 스피너 클릭을 조정합니다.

html5
<form>
  <label>
    Quantity:
    <input type="number" name="qty" min="1" max="99" step="1" value="1">
  </label>
  <label>
    Price:
    <input type="number" name="price" min="0" step="0.01">
  </label>
  <label>
    Date range:
    <input type="date" name="start" min="2024-01-01" max="2024-12-31">
  </label>
  <button>Submit</button>
</form>

Minlength & Maxlength

minlength와 maxlength가 텍스트 input과 textarea의 문자 수를 제한합니다. minlength는 필드에 값이 있을 때만 검증을 트리거합니다(필수 필드에는 required와 결합). maxlength는 한도를 넘는 입력을 하드 차단해 타이핑 자체를 막습니다.

html5
<form>
  <label>
    Username (3-20 chars):
    <input type="text" name="user" minlength="3" maxlength="20" required>
  </label>
  <label>
    Bio (max 280 chars):
    <textarea name="bio" maxlength="280"></textarea>
  </label>
  <button>Submit</button>
</form>

제약 검증 API

제약 검증 API는 validity.valid, valueMissing, typeMismatch, patternMismatch, tooShort, rangeOverflow 등을 노출합니다. setCustomValidity(msg)는 커스텀 메시지를 보여줍니다(빈 문자열을 넣으면 해제). checkValidity()는 불리언을 반환하고 invalid 이벤트를 발생시키며, reportValidity()는 UI도 보여줍니다.

html5
<form id="f">
  <label>
    Username:
    <input name="u" required minlength="3">
  </label>
  <button>Submit</button>
</form>

<script>
  const input = document.querySelector('#f input[name=u]');
  input.addEventListener('input', () => {
    if (input.validity.valueMissing) {
      input.setCustomValidity('Please pick a username.');
    } else if (input.validity.tooShort) {
      input.setCustomValidity('At least 3 characters.');
    } else {
      input.setCustomValidity('');
    }
  });
</script>

novalidate & formnovalidate

폼의 novalidate는 브라우저 검증을 완전히 끕니다 — JS로 검증할 때 유용합니다. submit 버튼의 formnovalidate는 그 버튼의 제출에만 검증을 건너뜁니다(예: 불완전한 데이터를 허용하는 '임시 저장'). 둘 다 폼은 여전히 제출합니다.

html5
<!-- Browser validation disabled for whole form -->
<form novalidate>
  <label>Email: <input type="email" name="e" required></label>
  <button>Save draft</button>
  <!-- Skip validation only for this button -->
  <button type="submit" formnovalidate>Cancel</button>
</form>
04

Canvas 그리기

Canvas 요소 & 2D 컨텍스트

canvas는 비트맵 드로잉 표면입니다. getContext('2d')가 2D 렌더링 컨텍스트를, 'webgl'은 3D 컨텍스트를 반환합니다. width/height 속성이 드로잉 버퍼 크기를 정합니다(CSS 크기 아님). 레티나에서 선명하게 렌더링하려면 버퍼를 devicePixelRatio만큼 스케일하세요. 폴백 콘텐츠는 태그 사이에 둡니다.

html5
<canvas id="cv" width="400" height="300">
  Your browser does not support canvas.
</canvas>

<script>
  const canvas = document.getElementById('cv');
  const ctx = canvas.getContext('2d');
  // High-DPI scaling
  const dpr = window.devicePixelRatio || 1;
  canvas.width = 400 * dpr;
  canvas.height = 300 * dpr;
  ctx.scale(dpr, dpr);
</script>

사각형 그리기

fillRect(x, y, w, h)는 채워진 사각형을, strokeRect는 외곽선만, clearRect는 픽셀을 투명하게 지웁니다. fillStyle과 strokeStyle은 색, 그라디언트, 패턴을 받습니다. lineWidth가 선 두께에 영향을 주며 경로 가장자리를 중심으로 합니다.

html5
<script>
  const ctx = canvas.getContext('2d');
  // Filled rectangle
  ctx.fillStyle = '#3498db';
  ctx.fillRect(10, 10, 100, 50);
  // Outlined rectangle
  ctx.strokeStyle = '#e74c3c';
  ctx.lineWidth = 3;
  ctx.strokeRect(130, 10, 100, 50);
  // Clear a rectangle (erase)
  ctx.clearRect(50, 20, 40, 30);
</script>

경로 & 선

beginPath가 새 경로를 시작합니다. moveTo는 그리지 않고 펜 위치를 정하고, lineTo가 선분을 추가합니다. closePath는 마지막 점을 시작점과 연결합니다. 렌더링하려면 fill()과/또는 stroke()를 호출하세요. 호(arc), 곡선(quadraticCurveTo, bezierCurveTo), 사각형도 경로에 추가할 수 있습니다.

html5
<script>
  const ctx = canvas.getContext('2d');
  ctx.beginPath();
  ctx.moveTo(20, 20);          // starting point
  ctx.lineTo(180, 20);         // top edge
  ctx.lineTo(100, 140);        // bottom corner
  ctx.closePath();             // back to start
  ctx.fillStyle = 'rgba(46,204,113,0.6)';
  ctx.fill();
  ctx.stroke();
</script>

텍스트 그리기

font는 CSS font와 같은 축약형을 씁니다. textAlign(start, end, left, right, center)과 textBaseline(top, middle, alphabetic, bottom)이 정렬을 제어합니다. fillText는 채워진 텍스트를, strokeText는 외곽선만 그립니다. measureText('foo').width가 렌더링된 너비를 반환합니다.

html5
<script>
  const ctx = canvas.getContext('2d');
  ctx.font = '600 24px system-ui, sans-serif';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = '#2c3e50';
  ctx.fillText('Hello Canvas', 200, 150);
  ctx.lineWidth = 1;
  ctx.strokeStyle = '#bdc3c7';
  ctx.strokeText('Outlined', 200, 200);
</script>

이미지 그리기

drawImage는 img, canvas, video 요소를 받을 수 있습니다. 3개 인수는 원본 크기로, 5개 인수는 w/h로 스케일하며, 9개 인수는 처음 넷이 소스 사각형(크롭), 마지막 넷이 대상 사각형입니다. 그리기 전에 onload를 기다리세요 — 아니면 이미지가 나타나지 않을 수 있습니다.

html5
<script>
  const img = new Image();
  img.src = 'pic.jpg';
  img.onload = () => {
    ctx.drawImage(img, 0, 0);                      // full size
    ctx.drawImage(img, 0, 0, 100, 75);             // scaled
    // Source crop -> destination
    ctx.drawImage(img, 32, 32, 64, 64, 200, 0, 64, 64);
  };
</script>

그라디언트

createLinearGradient(x0, y0, x1, y1)와 createRadialGradient(x0, y0, r0, x1, y1, r1)가 그라디언트를 정의합니다. addColorStop(offset, color)은 0~1 오프셋으로 색 정지점을 추가합니다. 표준 색 문자열을 전달하세요 — 형식이 섞이면(hex와 rgba 혼용) 보간이 깨질 수 있습니다. 그라디언트를 fillStyle이나 strokeStyle에 할당하세요.

html5
<script>
  // Linear gradient
  const lg = ctx.createLinearGradient(0, 0, 200, 0);
  lg.addColorStop(0, '#1e90ff');
  lg.addColorStop(1, '#ffffff');
  ctx.fillStyle = lg;
  ctx.fillRect(0, 0, 200, 80);

  // Radial gradient
  const rg = ctx.createRadialGradient(100, 180, 5, 100, 180, 80);
  rg.addColorStop(0, 'rgba(255,200,0,1)');
  rg.addColorStop(1, 'rgba(255,200,0,0)');
  ctx.fillStyle = rg;
  ctx.fillRect(0, 100, 200, 160);
</script>
05

인라인 SVG

SVG 요소 기본

인라인 SVG는 svg 요소를 쓰며 width/height가 표시 크기, viewBox가 좌표계입니다. xmlns는 SVG를 독립적으로 쓸 때 필수이고 인라인에서는 선택입니다. SVG는 벡터 기반입니다: 어떤 크기에서도 선명하게 스케일되며 일반 HTML처럼 검색과 CSS 스타일링이 됩니다.

html5
<svg width="200" height="120" viewBox="0 0 200 120"
     xmlns="http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="180" height="100"
        fill="#3498db" rx="8" />
  <text x="100" y="65" text-anchor="middle"
        fill="white" font-size="18">SVG</text>
</svg>

기본 도형

SVG 프리미티브에는 rect, circle, ellipse, line, polyline(열림), polygon(닫힘)이 있습니다. cx/cy가 중심 좌표이고 r이 반지름입니다. fill이 내부 색이고 stroke가 외곽선입니다. stroke-width가 외곽선 두께를 정합니다. 모든 속성은 CSS로도 설정할 수 있습니다.

html5
<svg width="240" height="120" viewBox="0 0 240 120">
  <rect x="10" y="10" width="80" height="80" fill="#e74c3c" />
  <circle cx="150" cy="50" r="40" fill="#2ecc71" />
  <ellipse cx="200" cy="60" rx="30" ry="18" fill="#f1c40f" />
  <line x1="10" y1="110" x2="230" y2="110" stroke="#333" stroke-width="2" />
  <polyline points="10,100 60,70 110,100 160,70"
            fill="none" stroke="#9b59b6" stroke-width="3" />
</svg>

Path

path가 가장 강력한 SVG 요소로, d 속성의 명령으로 그립니다. M = moveTo, L = lineTo, H/V = 수평/수직선, C = 3차 베지어, Q = 2차 베지어, A = 호, Z = 경로 닫기. 소문자는 상대 좌표를 씁니다. 에디터가 수출한 대부분의 SVG는 path를 씁니다.

html5
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- M=moveTo, L=lineTo, C=cubicBezier, Z=closePath -->
  <path d="M 10 80
           C 40 10, 90 10, 120 80
           L 180 80 Z"
        fill="none" stroke="#3498db" stroke-width="3" />
  <!-- A=arc -->
  <path d="M 10 100 A 90 90 0 0 1 190 100"
        fill="none" stroke="#e74c3c" stroke-width="2" />
</svg>

SVG의 텍스트

text는 확장 가능하고 선택 가능한 텍스트를 렌더링합니다. x/y가 베이스라인을 위치시킵니다. text-anchor(start/middle/end)와 dominant-baseline이 정렬을 제어합니다. tspan은 세그먼트별 스타일, 위치, 줄바꿈을 허용합니다. SVG 텍스트는 어떤 줌에서도 선명하며 접근 가능합니다 — canvas에 그린 텍스트와 다릅니다.

html5
<svg width="300" height="100" viewBox="0 0 300 100">
  <text x="20" y="40" font-family="system-ui" font-size="20"
        fill="#2c3e50">Plain text</text>
  <text x="20" y="75" font-size="20" fill="#e74c3c"
        text-decoration="underline">Underlined</text>
  <text x="180" y="50">
    <tspan fill="#3498db">Blue</tspan>
    <tspan fill="#27ae60">Green</tspan>
  </text>
</svg>

그라디언트 & 패턴

그라디언트는 defs 안에 있으며 fill='url(#id)'로 id를 참조합니다. linearGradient는 x1/y1/x2/y2를 씁니다(기본 objectBoundingBox, 0-1). radialGradient의 기본은 중심 원입니다. stop 요소가 색 정지점을 정의합니다. defs는 패턴, 클립 경로, 재사용 심볼도 담습니다.

html5
<svg width="220" height="120" viewBox="0 0 220 120">
  <defs>
    <linearGradient id="g1" x1="0" y1="0" x2="1" y2="0">
      <stop offset="0%" stop-color="#1e90ff" />
      <stop offset="100%" stop-color="#ffffff" />
    </linearGradient>
    <radialGradient id="g2">
      <stop offset="0%" stop-color="#f1c40f" />
      <stop offset="100%" stop-color="#e67e22" />
    </radialGradient>
  </defs>
  <rect x="10" y="10" width="90" height="90" fill="url(#g1)" />
  <circle cx="160" cy="55" r="45" fill="url(#g2)" />
</svg>

인라인 SVG vs Canvas

SVG는 해상도 독립적이고 각 도형이 스타일링과 이벤트 부착이 가능한 DOM 노드입니다 — 아이콘, 요소 수가 적은 차트, 접근 가능한 그래픽에 이상적. Canvas는 단일 비트맵으로 수천 개 객체나 픽셀 조작(게임, 이미지 처리)에 더 빠르지만 확장되지 않고 DOM 접근이 불가합니다.

html5
<!-- SVG: vector, DOM-accessible, scalable -->
<svg width="100" height="100" viewBox="0 0 100 100">
  <circle id="c" cx="50" cy="50" r="40" fill="#3498db" />
</svg>
<button onclick="document.getElementById('c')
  .setAttribute('r','20')">Shrink</button>

<!-- Canvas: bitmap, pixel-based, faster for many objects -->
<canvas id="cv" width="100" height="100"></canvas>
06

오디오 & 비디오

Video 요소

video는 플러그인 없이 비디오를 삽입합니다. controls가 네이티브 UI를 보여주고, poster가 재생 전 썸네일입니다. 여러 source 요소로 브라우저가 첫 지원 코덱을 고릅니다. 태그 사이의 폴백 텍스트는 미지원 브라우저에서 표시됩니다. 레이아웃 시프트를 피하려면 항상 width/height를 포함하세요.

html5
<video controls width="640" poster="cover.jpg">
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.webm" type="video/webm">
  Your browser does not support the video tag.
</video>

Audio 요소

audio는 시각적 크기가 없다는 점만 빼면 video처럼 동작합니다. controls가 재생/일시정지/탐색/볼륨 UI를 더합니다. controls가 없으면 요소가 보이지 않아 JS로 제어해야 합니다. 크로스 브라우저 지원을 위해 여러 소스(mp3, ogg)를 제공하세요. autoplay는 muted가 아니면 브라우저가 차단할 수 있습니다.

html5
<audio controls>
  <source src="song.mp3" type="audio/mpeg">
  <source src="song.ogg" type="audio/ogg">
  Your browser does not support audio.
</audio>

<!-- Simple single-source -->
<audio src="beep.mp3" autoplay></audio>

다중 소스

브라우저는 재생 가능한 type의 첫 소스를 고릅니다. codecs 매개변수를 포함하면 다운로드 없이 판단이 됩니다. 페이로드가 작은 현대 포맷(webm/av1)을 먼저 나열하고 mp4를 만능 폴백으로 두세요. 태그 안의 다운로드 링크가 우아한 폴백입니다.

html5
<video controls>
  <source src="clip.webm" type='video/webm; codecs="vp9, opus"'>
  <source src="clip.mp4"  type='video/mp4; codecs="hvc1"'>
  <source src="clip.ogv"  type="video/ogg">
  <p>Download <a href="clip.mp4">clip.mp4</a></p>
</video>

Track 요소 (자막)

track은 WebVTT(.vtt) 파일로 시간 지정 텍스트 트랙을 추가합니다. kind는 subtitles, captions, descriptions, chapters, metadata가 될 수 있습니다. srclang이 언어를 선언하고, label이 메뉴에 표시되며, default가 초기 트랙을 고릅니다. 자막은 접근성에 필수이고 SEO도 개선합니다.

html5
<video controls>
  <source src="talk.mp4" type="video/mp4">
  <track kind="subtitles" src="talk.en.vtt"
         srclang="en" label="English" default>
  <track kind="captions" src="talk.en.cc.vtt"
         srclang="en" label="English CC">
  <track kind="chapters" src="talk.chapters.vtt"
         srclang="en" label="Chapters">
</video>

미디어 속성

autoplay는 자동 재생을 시작하지만 muted도 함께 설정되지 않으면 차단됩니다. loop는 영원히 반복합니다. playsinline은 iOS의 강제 전체화면을 막습니다(인라인 배경에 필수). preload는 none, metadata(지속 시간/크기만), auto(전체 버퍼링)가 될 수 있습니다. 대역폭을 위해 autoplay + preload=auto는 피하세요.

html5
<video src="bg.mp4"
       autoplay muted loop
       playsinline
       preload="auto"
       width="1280" height="720">
</video>

<video src="preview.mp4"
       controls
       preload="metadata"
       poster="preview.jpg">
</video>

미디어 API

HTMLMediaElement API는 play(), pause(), load(), currentTime, duration, volume, muted, playbackRate, readyState를 노출합니다. 이벤트에는 play, pause, timeupdate, ended, volumechange, loadedmetadata, waiting이 있습니다. controls를 숨기고 버튼을 이 메서드들에 연결해 커스텀 플레이어를 만드세요.

html5
<video id="v" src="movie.mp4"></video>
<button onclick="v.play()">Play</button>
<button onclick="v.pause()">Pause</button>
<input type="range" min="0" max="100" oninput="v.volume = this.value/100">

<script>
  const v = document.getElementById('v');
  v.addEventListener('timeupdate', () => {
    console.log(v.currentTime, '/', v.duration);
  });
  v.addEventListener('ended', () => alert('Done!'));
  // Jump 10s forward
  function skip() { v.currentTime += 10; }
</script>
07

지리 위치

getCurrentPosition

getCurrentPosition은 성공 콜백과 선택적 오류 콜백, 옵션 객체를 받습니다. position 객체는 coords.latitude, longitude, accuracy와 — 사용 가능하면 — altitude, heading, speed를 노출합니다. 지리 위치는 HTTPS(또는 localhost)에서만 동작하며 사용자 권한을 요청합니다.

html5
<script>
  if ('geolocation' in navigator) {
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        console.log('Latitude:', pos.coords.latitude);
        console.log('Longitude:', pos.coords.longitude);
        console.log('Accuracy:', pos.coords.accuracy, 'meters');
      },
      (err) => console.error(err.message),
      { enableHighAccuracy: true, timeout: 10000 }
    );
  }
</script>

위치 옵션

enableHighAccuracy는 시간과 배터리를 대가로 가장 정밀한 결과(GPS)를 요구합니다. timeout이 대기를 제한하며 초과하면 error.code가 TIMEOUT(3)입니다. maximumAge는 지정한 밀리초보다 새 것이면 브라우저가 캐시된 위치를 반환하게 해 반복 GPS 호출을 피합니다.

html5
<script>
  navigator.geolocation.getCurrentPosition(success, error, {
    enableHighAccuracy: true,  // use GPS, slower
    timeout: 5000,             // max wait in ms
    maximumAge: 60000          // accept cached fix up to 60s old
  });

  function success(pos) { /* ... */ }
  function error(err) { /* ... */ }
</script>

watchPosition

watchPosition은 위치가 바뀔 때마다 성공 콜백을 부르며 ID를 반환합니다. 그 ID를 clearWatch에 전달해 업데이트를 멈추세요. 내비게이션 앱에 필수입니다. 배터리를 신경 쓰세요 — 합리적인 업데이트 간격을 쓰고 필요 없을 때 감시를 멈추세요.

html5
<script>
  const watchId = navigator.geolocation.watchPosition(
    (pos) => updateMap(pos.coords),
    (err) => console.warn(err.message),
    { enableHighAccuracy: true }
  );

  // Stop tracking
  document.getElementById('stop').onclick = () => {
    navigator.geolocation.clearWatch(watchId);
  };
</script>

오류 처리

오류 콜백은 code와 message를 가진 GeolocationPositionError를 받습니다. PERMISSION_DENIED(1)는 사용자가 거부했거나 브라우저가 차단했다는 뜻이고, POSITION_UNAVAILABLE(2)은 기기가 위치를 못 구했다는 뜻이며, TIMEOUT(3)은 timeout 옵션보다 오래 걸렸다는 뜻입니다. 세 사례를 모두 우아하게 처리하세요.

html5
<script>
  navigator.geolocation.getCurrentPosition(
    (pos) => console.log(pos),
    (err) => {
      switch (err.code) {
        case err.PERMISSION_DENIED:  // 1
          console.log('User denied permission'); break;
        case err.POSITION_UNAVAILABLE: // 2
          console.log('Position unavailable'); break;
        case err.TIMEOUT:              // 3
          console.log('Timed out'); break;
      }
      console.log(err.message);
    }
  );
</script>

Permissions API

Permissions API는 프롬프트를 트리거하지 않고 권한 상태를 검사하게 합니다. query({ name: 'geolocation' })은 state가 granted, denied, prompt인 PermissionStatus를 반환합니다. 사용자가 다른 곳에서 권한을 주거나 뺄 때 반응하려면 onchange를 listen하세요. 지리 위치, 알림, 카메라, 마이크 등을 지원합니다.

html5
<script>
  navigator.permissions
    .query({ name: 'geolocation' })
    .then((result) => {
      // result.state: 'granted' | 'denied' | 'prompt'
      if (result.state === 'granted') {
        startTracking();
      } else if (result.state === 'prompt') {
        showEnableButton();
      } else {
        showInstructions();
      }
      result.onchange = () => console.log(result.state);
    });
</script>
08

웹 스토리지

localStorage 기본

localStorage는 만료 없이 문자열 키/값 쌍을 저장합니다; 데이터는 탭과 세션을 넘어 유지됩니다. 값은 문자열이므로 숫자와 불리언은 자동 변환됩니다. 한도는 오리진당 약 5MB입니다. 저장소는 동기식이며 메인 스레드를 막으니 큰 쓰기를 피하세요. 프라이빗 모드에서 접근 시 예외가 날 수 있으니 try/catch로 감싸세요.

html5
<script>
  // Store a value (strings only)
  localStorage.setItem('theme', 'dark');
  // Read a value
  const theme = localStorage.getItem('theme'); // 'dark'
  // Remove one key
  localStorage.removeItem('theme');
  // Remove everything
  localStorage.clear();

  // Number of stored keys
  console.log(localStorage.length);
</script>

sessionStorage

sessionStorage는 localStorage와 같은 API이지만 단일 탭으로 스코프되며 탭이 닫히면 지워집니다. 다단계 폼 초안, 임시 장바구니, CSRF 토큰 같은 일시적 데이터에 유용합니다. 같은 오리진이라도 데이터는 탭 간 공유되지 않습니다.

html5
<script>
  // sessionStorage works like localStorage but per-tab
  sessionStorage.setItem('cart', '3 items');
  console.log(sessionStorage.getItem('cart'));
  sessionStorage.removeItem('cart');

  // Survives a page reload but not a tab close
  // Also isolated per tab (not shared)
</script>

JSON 데이터 저장

웹 스토리지는 문자열만 저장하므로 객체와 배열에는 JSON.stringify와 JSON.parse를 쓰세요. 손상되었거나 손으로 편집된 데이터가 예외를 내므로 parse는 항상 try/catch로 감싸세요. 복잡한 데이터에는 키에 버전을 붙이세요(예: 'settings.v2') — 스키마 변경이 옛 데이터를 깨지 않게.

html5
<script>
  const settings = { theme: 'dark', fontSize: 16, lang: 'en' };

  // Serialize before saving
  localStorage.setItem('settings', JSON.stringify(settings));

  // Parse when reading
  try {
    const saved = JSON.parse(localStorage.getItem('settings'));
    console.log(saved.theme); // 'dark'
  } catch (e) {
    console.warn('Corrupted data', e);
  }
</script>

스토리지 이벤트

storage 이벤트는 localStorage나 sessionStorage가 바뀔 때 같은 오리진의 다른 모든 탭에서 발생합니다 — 변경한 탭에서는 발생하지 않습니다. 가장 단순한 크로스 탭 통신 채널입니다. 이벤트 객체는 key, oldValue, newValue, url, storageArea를 운반합니다. 탭 간 로그아웃, 테마 변경, 실시간 업데이트 동기화에 쓰세요.

html5
<script>
  // Listen in OTHER tabs (same origin) for changes
  window.addEventListener('storage', (e) => {
    console.log('Key changed:', e.key);
    console.log('Old value:', e.oldValue);
    console.log('New value:', e.newValue);
    console.log('URL:', e.url);
  });

  // The tab that calls setItem does NOT receive the event
  localStorage.setItem('count', '42');
</script>

스토리지 지우기

clear()는 오리진의 모든 키를 제거합니다 — 아껴 쓰고 사용자에게 확인하세요. key(n)는 인덱스 n의 키 이름을 반환하며 범위 밖이면 null입니다. 순회 순서는 구현 정의이므로 의존하지 마세요. 부분 정리에는 접두사(예: 'cache:')로 키를 나열해 루프에서 removeItem하세요.

html5
<script>
  // Remove a single key
  localStorage.removeItem('temp');

  // Wipe all keys for this origin
  localStorage.clear();

  // Iterate keys
  const keys = [];
  for (let i = 0; i < localStorage.length; i++) {
    keys.push(localStorage.key(i));
  }
  console.log(keys);

  // Indexed access (order is not guaranteed)
  localStorage.key(0);
</script>
09

IndexedDB

데이터베이스 열기

indexedDB.open(name, version)이 데이터베이스를 열거나 만듭니다. onupgradeneeded는 버전이 올라가거나 DB가 처음 만들어질 때 발생합니다 — 객체 스토어와 인덱스를 만들거나 바꿀 수 있는 유일한 곳입니다. 스키마를 바꿀 때마다 버전을 올리세요. 스토어에는 keyPath(키로 쓰일 프로퍼티)나 자동 증가 키가 필요합니다.

html5
<script>
  const request = indexedDB.open('MyDB', 1);

  request.onupgradeneeded = (e) => {
    const db = e.target.result;
    if (!db.objectStoreNames.contains('users')) {
      const store = db.createObjectStore('users', { keyPath: 'id' });
      store.createIndex('email', 'email', { unique: true });
    }
  };

  request.onsuccess = (e) => {
    const db = e.target.result;
    console.log('DB ready:', db.name, db.version);
  };

  request.onerror = (e) => console.error(e.target.error);
</script>

Object Store

객체 스토어는 테이블과 같습니다; 각 레코드가 키와 값(구조화 클론 가능한 어떤 객체든)을 가집니다. keyPath가 스토어에 어떤 프로퍼티가 키인지 알려줍니다. autoIncrement는 순차 정수 키를 부여합니다. 인덱스로 키가 아닌 프로퍼티로 조회할 수 있으며, unique: true가 그 필드의 중복을 막습니다.

html5
<script>
  request.onupgradeneeded = (e) => {
    const db = e.target.result;

    // With a key path
    const users = db.createObjectStore('users', { keyPath: 'id' });

    // Auto-incrementing integer key
    const logs = db.createObjectStore('logs', { autoIncrement: true });

    // Indexes for fast lookups
    users.createIndex('name', 'name', { unique: false });
    users.createIndex('email', 'email', { unique: true });
  };
</script>

데이터 추가

모든 연산은 db.transaction(storeName, mode)으로 만든 트랜잭션 안에서 일어납니다. 모드는 'readonly'(기본값) 또는 'readwrite'입니다. add()는 중복을 거부하고, put()은 업서트합니다. 트랜잭션은 모든 요청이 완료되면 자동 커밋되며 oncomplete를 listen하세요. 트랜잭션은 짧게 유지하세요 — 같은 스토어의 다른 트랜잭션을 막습니다.

html5
<script>
  function addUser(db, user) {
    const tx = db.transaction('users', 'readwrite');
    const store = tx.objectStore('users');
    store.add(user);          // throws on duplicate key
    // store.put(user);       // inserts OR overwrites

    tx.oncomplete = () => console.log('Saved');
    tx.onerror = () => console.error(tx.error);
  }

  addUser(db, { id: 1, name: 'Ada', email: '[email protected]' });
</script>

데이터 읽기

get(key)는 기본 키로 단일 레코드를 읽고, getAll()은 모든 레코드를 배열로 반환합니다. 키가 아닌 필드로 찾으려면 store.index(name)으로 인덱스를 열고 거기서 get/getAll을 호출하세요. 각 요청에는 onsuccess와 onerror가 있습니다. 결과는 event.target.result나 request.result에 있습니다.

html5
<script>
  const tx = db.transaction('users', 'readonly');
  const store = tx.objectStore('users');

  // By primary key
  const req = store.get(1);
  req.onsuccess = () => console.log(req.result);

  // By index
  const byEmail = store.index('email');
  byEmail.get('[email protected]').onsuccess = (e) => {
    console.log(e.target.result);
  };

  // All records
  store.getAll().onsuccess = (e) => {
    console.log(e.target.result); // array
  };
</script>

커서 & 인덱스

openCursor()는 레코드를 한 번에 하나씩 순회하게 합니다 — 메모리에 다 안 들어가는 큰 데이터셋에 이상적. 전진하려면 cursor.continue()를 호출하세요. cursor.update(value)가 현재 레코드를 수정하고, cursor.delete()가 제거합니다. IDBKeyRange(bound, only, lowerBound, upperBound)가 인덱스 쿼리의 범위를 정합니다 — 접두사나 범위 검색에 유용합니다.

html5
<script>
  const tx = db.transaction('users', 'readwrite');
  const store = tx.objectStore('users');

  // Iterate and modify
  const req = store.openCursor();
  req.onsuccess = (e) => {
    const cursor = e.target.result;
    if (cursor) {
      if (cursor.value.name === 'Ada') {
        cursor.value.role = 'admin';
        cursor.update(cursor.value);
      }
      cursor.continue();
    }
  };

  // Range query on an index
  const range = IDBKeyRange.bound('A', 'M');
  store.index('name').openCursor(range).onsuccess = (e) => { /* ... */ };
</script>
10

드래그 앤 드롭 API

드래그 가능하게 만들기

요소에 draggable='true'를 설정하면 드래그 가능해집니다. dragstart 이벤트는 드래그 시작 시 발생하며, dataTransfer.setData로 드롭 대상에 전달할 데이터를 포장하세요. effectAllowed(copy, move, link, all, none)가 의도한 연산을 힌트합니다. dragend는 드롭 여부와 무관하게 드래그가 끝나면 발생합니다.

html5
<div id="card" draggable="true">
  Drag me!
</div>

<script>
  const card = document.getElementById('card');
  card.addEventListener('dragstart', (e) => {
    e.dataTransfer.setData('text/plain', card.id);
    e.dataTransfer.effectAllowed = 'move';
    card.classList.add('dragging');
  });
  card.addEventListener('dragend', () => {
    card.classList.remove('dragging');
  });
</script>

드래그 이벤트

드롭을 받으려면 dragover와 drop 양쪽에서 반드시 preventDefault()를 호출해야 합니다 — 아니면 브라우저가 아무것도 하지 않습니다. dragenter/dragleave는 포인터가 대상에 들어가거나 나올 때 발생합니다. dropEffect(copy, move, link, none)가 커서를 제어합니다. drag 이벤트는 드래그 중 소스에서 계속 발생합니다.

html5
<script>
  // Events on the SOURCE element:
  //   dragstart, drag, dragend

  // Events on the TARGET element:
  //   dragenter, dragover, dragleave, drop

  const drop = document.getElementById('drop');
  drop.addEventListener('dragover', (e) => {
    e.preventDefault();                 // REQUIRED to allow drop
    e.dataTransfer.dropEffect = 'move';
  });
  drop.addEventListener('drop', (e) => {
    e.preventDefault();
    const id = e.dataTransfer.getData('text/plain');
    drop.appendChild(document.getElementById(id));
  });
</script>

DataTransfer

dataTransfer가 드래그 소스와 드롭 대상 사이에서 데이터를 운반합니다. setData(format, data)가 문자열을 저장하고, getData(format)가 읽습니다. 표준 형식에는 text/plain, text/uri-list, text/html, files가 있습니다. 커스텀 MIME 타입도 등록할 수 있습니다. 일부 브라우저는 보안상 getData를 drop 이벤트로 제한합니다.

html5
<script>
  card.addEventListener('dragstart', (e) => {
    // Multiple data types
    e.dataTransfer.setData('text/plain', 'Hello');
    e.dataTransfer.setData('text/uri-list', 'https://example.com');
    e.dataTransfer.setData('application/json', JSON.stringify({ a: 1 }));

    // Read in the drop handler
    // e.dataTransfer.getData('text/plain')
  });
</script>

드롭 존

흔한 패턴: dragenter/dragover에서 드롭 존을 하이라이트하고 dragleave/drop에서 해제. dataTransfer.files는 OS에서 파일을 드래그하면 FileList를 주며, 드래그 앤 드롭 업로드를 가능하게 합니다. dragover에서 항상 preventDefault하세요 — 아니면 drop 이벤트가 발생하지 않습니다. 중첩 요소가 있으면 dragenter/leave 카운터를 쓰세요.

html5
<style>
  .dropzone { border: 2px dashed #bbb; padding: 24px; }
  .dropzone.over { background: #eaf6ff; border-color: #3498db; }
</style>

<div class="dropzone" id="dz">Drop files here</div>

<script>
  const dz = document.getElementById('dz');
  dz.addEventListener('dragenter', () => dz.classList.add('over'));
  dz.addEventListener('dragover',  (e) => e.preventDefault());
  dz.addEventListener('dragleave', () => dz.classList.remove('over'));
  dz.addEventListener('drop', (e) => {
    e.preventDefault();
    dz.classList.remove('over');
    const files = e.dataTransfer.files;   // FileList
    for (const f of files) console.log(f.name, f.size);
  });
</script>

드래그 이미지

setDragImage(element, offsetX, offsetY)는 기본 드래그 고스트를 커스텀 요소로 대체합니다. 요소는 DOM에 있고 렌더링되어야 하므로 만들고, 추가하고, dragstart 뒤에 제거하세요. 오프셋이 커서를 이미지 왼쪽 위 기준으로 위치시킵니다. 이미지를 넘기지 않으면 브라우저가 드래그된 요소를 스크린샷합니다.

html5
<script>
  card.addEventListener('dragstart', (e) => {
    const ghost = document.createElement('div');
    ghost.textContent = 'Dragging card';
    ghost.style.cssText = 'position:absolute;top:-999px;' +
                          'padding:8px;background:#3498db;color:#fff;';
    document.body.appendChild(ghost);
    e.dataTransfer.setDragImage(ghost, 20, 20);
    setTimeout(() => document.body.removeChild(ghost), 0);
  });
</script>
11

Web Worker

Worker 기본

new Worker(url)이 스크립트 파일을 실행하는 백그라운드 스레드를 만듭니다. 통신은 postMessage와 onmessage이며, 데이터가 스레드 사이에 복사됩니다(구조화 클론). Worker는 DOM, window, document를 만질 수 없지만 — fetch, IndexedDB, setTimeout은 쓸 수 있습니다. UI가 반응성을 유지하도록 무거운 계산에 쓰세요.

html5
<!-- main.js -->
<script>
  const worker = new Worker('worker.js');

  worker.postMessage({ cmd: 'sum', nums: [1, 2, 3] });

  worker.onmessage = (e) => {
    console.log('Result:', e.data);   // 6
  };

  worker.onerror = (e) => {
    console.error(e.message, e.filename, e.lineno);
  };
</script>

Worker 스크립트

worker 안에서 self(또는 this)가 전역 스코프입니다 — postMessage와 onmessage가 여기에 붙습니다. window나 document는 없습니다. Worker는 fetch, importScripts(), setTimeout/setInterval, IndexedDB를 쓸 수 있습니다. importScripts('a.js','b.js')가 다른 스크립트를 동기로 워커에 로드합니다. 각 워커는 자신의 격리에서 실행됩니다.

html5
// worker.js
self.onmessage = (e) => {
  const { cmd, nums } = e.data;
  if (cmd === 'sum') {
    let total = 0;
    for (const n of nums) total += n;
    self.postMessage(total);
  } else if (cmd === 'heavy') {
    const result = doExpensiveWork();
    self.postMessage(result);
  }
};

function doExpensiveWork() {
  // ... long-running computation
  return 'done';
}

메시지 전송

postMessage(data, transferables)는 데이터를 구조화 클론으로 복사해 보냅니다. 두 번째 인수에 ArrayBuffer, MessagePort, ImageBitmap 배열을 전달하면 복사 대신 소유권을 TRANSFER합니다 — 큰 버퍼에 훨씬 빠르지만 원본이 전송 스레드에서 쓸 수 없게 됩니다.

html5
<script>
  const w = new Worker('worker.js');

  // Plain object
  w.postMessage({ type: 'start' });

  // Transferable: zero-copy move of a buffer
  const buffer = new ArrayBuffer(1024);
  w.postMessage(buffer, [buffer]);
  // buffer is now "neutered" in main thread

  // Two-way communication
  w.onmessage = (e) => console.log('Worker said:', e.data);
</script>

이전 가능(Transferable) 객체

이전 가능 객체(ArrayBuffer, MessagePort, ImageBitmap, OffscreenCanvas)는 복사 없이 스레드 사이를 이동합니다. transferControlToOffscreen은 canvas를 워커에 넘기고, 워커가 이를 독립적으로 렌더링합니다 — 메인 스레드가 바쁠 때도 부드러운 애니메이션에 좋습니다. 메인 스레드는 이전된 객체 접근을 잃습니다.

html5
<script>
  // Send a canvas ImageBitmap to a worker for processing
  const offscreen = canvas.transferControlToOffscreen();
  const worker = new Worker('paint.js');
  worker.postMessage({ canvas: offscreen }, [offscreen]);

  // Now the worker draws directly to the canvas
  // without round-trips to the main thread.
</script>

<!-- paint.js -->
self.onmessage = (e) => {
  const ctx = e.data.canvas.getContext('2d');
  ctx.fillStyle = '#3498db';
  ctx.fillRect(0, 0, 100, 100);
};

Shared Worker

SharedWorker는 같은 오리진의 여러 탭이 공유하는 단일 워커입니다. 각 연결이 connect 이벤트로 MessagePort를 받습니다. 크로스 탭 상태(실시간 카운트, 공유 캐시)나 단일 WebSocket 팬아웃에 쓰세요. SharedWorker는 iOS의 Safari에서 지원되지 않고 특이점이 있으니 — 의존하기 전에 테스트하세요.

html5
<!-- main.js -->
<script>
  const sw = new SharedWorker('shared.js');
  sw.port.onmessage = (e) => console.log('Broadcast:', e.data);
  sw.port.start();
  sw.port.postMessage({ from: 'tab-A' });
</script>

<!-- shared.js -->
const ports = new Set();
self.onconnect = (e) => {
  const port = e.ports[0];
  ports.add(port);
  port.onmessage = (ev) => {
    // Broadcast to every connected tab
    for (const p of ports) p.postMessage(ev.data);
  };
  port.start();
};
12

WebSocket

연결 열기

new WebSocket(url)이 지속적인 양방향 연결을 엽니다. 프로덕션에서는 wss://(TLS)를 쓰세요 — ws://는 평문이며 HTTPS 페이지에서 차단됩니다. readyState는 CONNECTING(0) → OPEN(1) → CLOSING(2) → CLOSED(3)으로 갑니다. open, message, error, close 이벤트를 listen하세요.

html5
<script>
  const ws = new WebSocket('wss://echo.example.com/chat');

  ws.addEventListener('open', () => {
    console.log('Connected');
    ws.send('Hello server!');
  });

  ws.addEventListener('message', (e) => {
    console.log('Received:', e.data);
  });

  ws.addEventListener('close', (e) => {
    console.log('Closed', e.code, e.reason);
  });
</script>

메시지 전송

send()는 문자열, Blob, ArrayBuffer, ArrayBufferView를 받습니다. 구조화 데이터는 먼저 JSON.stringify하고 반대편에서 파싱하세요. open 전에 보내면 메시지가 대기열에 들어가지만, 안전하게 readyState === OPEN을 확인하세요. 프로토콜은 풀 듀플렉스입니다 — 어느 쪽이든 언제든 보낼 수 있습니다.

html5
<script>
  // Strings
  ws.send('plain text');

  // JSON
  ws.send(JSON.stringify({ type: 'chat', text: 'hi' }));

  // Binary
  const blob = new Blob([new Uint8Array([1,2,3])]);
  ws.send(blob);
  ws.send(new ArrayBuffer(8));

  // Check state before sending
  if (ws.readyState === WebSocket.OPEN) ws.send(data);
</script>

메시지 수신

message 이벤트가 e.data를 문자열(텍스트), Blob(바이너리 기본값), ArrayBuffer(ws.binaryType = 'arraybuffer' 설정)로 전달합니다. 텍스트 프로토콜에는 JSON이 가장 흔합니다. 바이너리에는 파일/이미지에 Blob, 숫자 파싱에 ArrayBuffer를 고르세요. 양쪽이 모양에 동의하도록 메시지 스키마를 정의하세요.

html5
<script>
  ws.addEventListener('message', (e) => {
    // Text messages: e.data is a string
    if (typeof e.data === 'string') {
      const msg = JSON.parse(e.data);
      console.log(msg.type, msg.text);
    }
    // Binary: e.data is a Blob or ArrayBuffer
    else {
      e.data.arrayBuffer().then((buf) => {
        const view = new DataView(buf);
        console.log(view.getInt32(0));
      });
    }
  });

  // Force binary type
  ws.binaryType = 'arraybuffer';
</script>

오류 & 종료

error 이벤트는 보안상 세부가 적습니다; 이후 close 이벤트를 확인하세요. close(code, reason)가 깔끔한 종료를 시작합니다; 코드 1000은 정상 종료이고, 1006은 close 프레임 없이 연결이 끊겼음을 뜻합니다(네트워크 문제). 코드 4000-4999는 애플리케이션용입니다. wasClean은 양쪽이 핸드셰이크를 완료했을 때만 true입니다.

html5
<script>
  ws.addEventListener('error', (e) => {
    console.error('Socket error', e);
  });

  ws.addEventListener('close', (e) => {
    console.log('code:', e.code, 'reason:', e.reason, 'clean:', e.wasClean);
  });

  // Close gracefully (1000 = normal closure)
  ws.close(1000, 'goodbye');

  // Common codes:
  //   1000 normal, 1001 going away, 1006 abnormal (no close frame)
  //   4000-4999 app-defined
</script>

재연결

브라우저는 자동 재연결하지 않으므로 지수 백오프로 직접 구현하세요(delay = min(base * 2^retry, max)). 죽은 소켓이 감지·종료되도록 주기적 ping을 보내세요. close 시 재연결하되 재시도 간격에 상한을 두어 서버를 때리지 않게 하세요. 성공적으로 연결되면 재시도 카운터를 초기화하세요.

html5
<script>
  let ws;
  let retry = 0;

  function connect() {
    ws = new WebSocket('wss://example.com/live');
    ws.onopen = () => { retry = 0; console.log('open'); };
    ws.onmessage = (e) => console.log(e.data);
    ws.onclose = () => {
      const delay = Math.min(1000 * 2 ** retry, 30000);
      retry++;
      setTimeout(connect, delay);
    };
  }
  connect();

  // Heartbeat to detect dead connections
  setInterval(() => {
    if (ws.readyState === WebSocket.OPEN) ws.send('ping');
  }, 30000);
</script>
13

History API

pushState

pushState(state, title, url)는 세션 히스토리에 새 항목을 추가하고 주소창을 갱신하며 페이지를 리로드하지 않습니다 — 클라이언트 측 라우팅의 핵심입니다. URL은 같은 오리진이어야 하며 아니면 pushState가 예외를 냅니다. title 인수는 현재 브라우저가 무시합니다. state 객체는 직렬화 가능하며 history.state로 회수됩니다.

html5
<script>
  // Add a new entry WITHOUT reloading
  history.pushState(
    { page: 'about' },      // state object
    'About',                // title (ignored by most browsers)
    '/about'                // URL
  );

  console.log(history.length);     // entries count
  console.log(history.state);      // { page: 'about' }
</script>

replaceState

replaceState(state, title, url)는 pushState와 같지만 새 항목을 추가하는 대신 현재 항목을 교체합니다 — 뒤로/앞으로가 원래 항목을 건너뜁니다. 히스토리를 오염시키지 않고 URL이나 상태를 갱신할 때 쓰세요 — 예: 사용자가 '뒤로 가기'로 되돌리길 원치 않는 필터 적용 뒤.

html5
<script>
  // Replace the CURRENT entry (no new history item)
  history.replaceState(
    { page: 'home', tab: 'featured' },
    '',
    '/home?tab=featured'
  );

  // Useful for: cleaning up redirects, updating URL after
  // AJAX filter changes, or normalizing the entry URL.
</script>

popstate 이벤트

popstate는 사용자가 뒤로/앞으로를 클릭하거나 history.go/back/forward가 호출될 때 발생합니다 — pushState/replaceState에서는 발생하지 않습니다. event.state는 탐색 대상 항목의 state 객체입니다. 대부분의 SPA 라우터가 navigate()와 popstate 핸들러 양쪽에서 렌더 함수를 호출해 모든 탐색이 뷰를 갱신하게 합니다.

html5
<script>
  window.addEventListener('popstate', (e) => {
    console.log('Location:', location.pathname);
    console.log('State:', e.state);
    renderRoute(location.pathname);
  });

  function navigate(path) {
    history.pushState({ path }, '', path);
    renderRoute(path);
  }

  // NOTE: pushState/replaceState do NOT fire popstate.
  // Only back/forward (and history.go) do.
</script>

탐색 메서드

back(), forward(), go(delta)가 세션 히스토리를 이동합니다; go(0)은 리로드입니다. history.length는 현재 세션의 항목 수이며 브라우저가 상한을 둡니다. 이 메서드들은 비동기입니다 — 탐색이 완료되면 popstate가 발생합니다. 범위 밖으로 go하면 아무것도 하지 않습니다.

html5
<script>
  history.back();              // go back one entry
  history.forward();           // go forward one entry
  history.go(-2);              // go back two entries
  history.go(2);               // go forward two entries
  history.go(0);               // reload current page

  if (history.length === 1) {
    console.log('First page in this tab');
  }
</script>

SPA 라우팅

미니멀한 SPA 라우터: 내부 링크 클릭을 가로채고, URL 갱신을 pushState로 하고, 새 뷰를 렌더링합니다. 뒤로/앞으로가 동작하도록 popstate를 처리하세요. 내부 링크 표시에는 data-link나 클래스를 쓰고, 외부 링크나 target=_blank는 건너뛰세요. 실제 프레임워크는 중첩 라우트, 파라미터, 가드, 스크롤 복원을 추가합니다.

html5
<script>
  document.body.addEventListener('click', (e) => {
    const a = e.target.closest('a');
    if (!a || !a.matches('[data-link]')) return;
    if (a.origin !== location.origin) return;

    e.preventDefault();
    history.pushState({ path: a.pathname }, '', a.pathname);
    render(a.pathname);
  });

  window.addEventListener('popstate', () => render(location.pathname));

  function render(path) {
    fetch(path, { headers: { 'X-Ajax': '1' } })
      .then((r) => r.text())
      .then((html) => {
        document.querySelector('#app').innerHTML = html;
      });
  }
</script>
14

인라인 시맨틱 요소

time 요소

time은 특정 날짜, 시간, 지속 기간을 나타냅니다. 기계 판독 값은 datetime 속성에(YYYY-MM-DD, HH:MM, 또는 시간대가 있는 완전한 ISO 8601), 사람용 텍스트는 콘텐츠로 둡니다. 검색 엔진과 캘린더 앱이 datetime으로 이벤트를 추출합니다. datetime이 없으면 콘텐츠 자체가 유효한 날짜 문자열이어야 합니다.

html5
<p>
  Published on
  <time datetime="2024-07-04">July 4, 2024</time>.
</p>
<p>
  Event starts at
  <time datetime="2024-07-04T19:00-05:00">7 PM EST</time>.
</p>
<p>
  Open
  <time datetime="09:00">9:00 AM</time>-
  <time datetime="17:00">5:00 PM</time> daily.
</p>

mark 요소

mark는 사용자의 현재 맥락과 관련된 텍스트를 하이라이트합니다 — 검색어 매칭이나 사용자가 추가한 메모처럼. strong이나 em과 달리 의미적 강조는 없습니다 — 시각적 하이라이트일 뿐입니다. 기본 스타일은 노란 배경입니다. 인용자가 주목시키려는 텍스트를 표시하는 blockquote 안에서도 유용합니다.

html5
<p>
  The function <code>querySelector()</code> returns the
  first match, while <mark>querySelectorAll()</mark>
  returns a static NodeList.
</p>

<p>
  Search results: <mark>HTML5</mark> is the latest
  version of the Hypertext Markup Language.
</p>

details & summary

details는 사용자가 펼치거나 접을 수 있는 토글 위젯을 만듭니다 — JS가 필요 없습니다. summary가 항상 보이는 라벨이며 클릭하면 토글됩니다. 기본으로 펼치려면 open 속성을 추가하세요. 열리거나 닫히면 toggle 이벤트가 발생합니다. FAQ, 고급 설정, 콘텐츠의 점진적 공개에 좋습니다.

html5
<details>
  <summary>What is HTML5?</summary>
  <p>HTML5 is the fifth major revision of the HTML standard,
  introducing semantic elements, new form controls, and APIs
  for graphics, media, and offline apps.</p>
</details>

<details open>
  <summary>System requirements</summary>
  <ul>
    <li>Modern browser (Chrome, Firefox, Safari, Edge)</li>
    <li>JavaScript enabled</li>
  </ul>
</details>

dialog 요소

dialog는 모달이나 논모달 박스를 나타냅니다. show()는 논모달로 열고, showModal()은 배경과 나머지 페이지가 inert가 된 모달로 엽니다. 폼의 method='dialog'는 대화상자를 닫고 returnValue를 클릭된 버튼의 값으로 설정합니다. close 이벤트는 닫힌 뒤 발생합니다. ::backdrop이 오버레이를 스타일링합니다.

html5
<button onclick="dlg.showModal()">Open dialog</button>

<dialog id="dlg">
  <form method="dialog">
    <p>Are you sure?</p>
    <menu>
      <button value="cancel">Cancel</button>
      <button value="confirm">OK</button>
    </menu>
  </form>
</dialog>

<script>
  const dlg = document.getElementById('dlg');
  dlg.addEventListener('close', () => {
    console.log('User chose:', dlg.returnValue);
  });
</script>

abbr, cite & q

abbr은 title로 약어를 확장합니다(hover 툴팁)이며 스크린 리더를 돕습니다. cite는 작품의 제목(책, 기사, 영화)을 표시합니다 — 저자가 아닙니다. q는 인라인 인용입니다(브라우저가 따옴표 추가); blockquote는 블록 수준입니다. dfn은 용어의 정의 인스턴스를 표시하며, 이후 사용은 a로 링크할 수 있습니다.

html5
<p>
  <abbr title="World Health Organization">WHO</abbr>
  was founded in 1948.
</p>

<p>
  As <cite>MDN Web Docs</cite> notes,
  <q>HTML is the standard markup language.</q>
</p>

<p>
  Use <dfn>semantics</dfn> to describe the meaning of
  content, then refer to it normally.
</p>
15

반응형 디자인

Meta Viewport

viewport 메타 태그는 모바일 브라우저에게 기기 너비를 레이아웃 뷰포트로 쓰고 스케일 1에서 시작하라고 알립니다. 없으면 폰이 980px 폭인 척합니다. initial-scale=1이 로드 시 줌을 막습니다. viewport-fit=cover는 env(safe-area-inset-*)과 함께 노치 영역을 쓰게 합니다. user-scalable=no는 피하세요 — 접근성을 깨뜨립니다.

html5
<head>
  <meta name="viewport"
        content="width=device-width, initial-scale=1, viewport-fit=cover">
</head>

<!-- Without this tag, mobile browsers render the page at a
     ~980px "desktop" width and shrink it down, making text
     unreadable. -->

<!-- viewport-fit=cover lets content extend into the notch
     area on iPhone X+. -->

Picture 요소

picture는 미디어 조건에 따라 다른 이미지를 서빙하게 합니다(아트 디렉션). 브라우저는 media가 맞는 첫 source를 고르고 나머지는 무시합니다. img는 폴백으로 필수이며 alt 텍스트를 제공합니다. 리사이즈만이 아니라 브레이크포인트마다 이미지를 완전히 자르거나 바꿔야 할 때 쓰세요.

html5
<picture>
  <!-- Art direction: different image per viewport -->
  <source media="(min-width: 800px)" srcset="wide.jpg">
  <source media="(orientation: portrait)" srcset="tall.jpg">
  <img src="default.jpg" alt="A responsive photo">
</picture>

<!-- Browser picks the first matching <source>,
     falling back to the <img>. -->

srcset & sizes

srcset은 고유 너비(480w = 480px 폭)와 함께 이미지 후보를 나열합니다. sizes는 각 브레이크포인트에서 이미지가 얼마나 넓게 표시될지 브라우저에 알립니다. 브라우저가 뷰포트와 기기 픽셀 비율에 따라 최적 후보를 고릅니다 — JS가 필요 없습니다. 같은 이미지가 다른 해상도만 필요할 때 쓰세요.

html5
<img src="small.jpg"
     srcset="small.jpg 480w,
             medium.jpg 800w,
             large.jpg  1200w"
     sizes="(max-width: 600px) 100vw,
            (max-width: 1200px) 50vw,
            33vw"
     alt="A responsive photo">

뷰포트 단위

vw와 vh는 뷰포트 너비/높이의 백분율입니다. 모바일에서 100vh는 URL 바를 포함할 수 있어 떨림을 유발합니다 — dvh(동적), svh(작음), lvh(큼)를 선호하세요. clamp(min, preferred, max)가 너무 작거나 크지 않은 유동 타이포그래피의 가장 깔끔한 방법입니다. vmin/vmax는 짧은/긴 쪽을 씁니다.

html5
<style>
  .hero { height: 100vh; }           /* full viewport height */
  .half { width: 50vw; }             /* half the viewport width */

  /* Responsive typography */
  h1 {
    font-size: clamp(1.5rem, 4vw + 1rem, 3rem);
  }

  /* Use dvh/svh/lvh to handle mobile browser UI bars */
  .hero { height: 100dvh; }
</style>

type이 있는 picture

type이 있는 source로 JPEG/PNG 폴백과 함께 현대 이미지 형식을 서빙합니다. 브라우저는 지원하는 첫 타입을 고르고 나머지는 무시합니다. AVIF와 WebP는 같은 품질에서 JPEG보다 30-50% 작은 파일을 제공합니다. img의 loading='lazy'와 결합하면 가장 효율적인 이미지 전달 방법입니다.

html5
<picture>
  <!-- Modern format first, smaller file size -->
  <source type="image/avif" srcset="photo.avif">
  <source type="image/webp" srcset="photo.webp">
  <img src="photo.jpg" alt="Optimized photo" loading="lazy">
</picture>

<!-- Browser picks the first type it supports.
     AVIF and WebP are ~30-50% smaller than JPEG/PNG. -->
16

접근성 (ARIA)

ARIA 역할

ARIA 역할은 보조 기술에 요소의 기능을 알리지만, ARIA의 첫 규칙은 이것입니다: 네이티브 HTML 요소가 있으면 쓰지 마세요. header, nav, main, article, footer는 이미 banner, navigation, main, article, contentinfo 역할을 노출합니다. ARIA는 네이티브 등가물이 없는 커스텀 위젯(tab, dialog, slider, menu)에 쓰고, 역할은 키보드 지원과 짝지으세요.

html5
<div role="banner">           <!-- like <header> -->
  <h1>Site title</h1>
</div>

<div role="navigation">       <!-- like <nav> -->
  <a href="/">Home</a>
</div>

<div role="main">             <!-- like <main> -->
  <div role="article">        <!-- like <article> -->
    <p>Content</p>
  </div>
</div>

<button role="button" aria-pressed="false">Toggle</button>

aria-label & aria-labelledby

aria-label은 보이는 텍스트가 없을 때(아이콘 전용 버튼 등) 접근 가능한 이름을 제공합니다. aria-labelledby는 이름으로 쓸 보이는 텍스트의 id를 참조합니다 — 제목이 이미 섹션에 라벨을 붙일 때 유용. 폼 필드에는 보이는 <label for>를 권합니다. aria-describedby는 라벨 뒤에 읽히는 힌트 텍스트를 가리킵니다.

html5
<button aria-label="Close menu">×</button>

<nav aria-labelledby="main-nav-heading">
  <h2 id="main-nav-heading" class="sr-only">Main navigation</h2>
  <ul>...</ul>
</nav>

<input id="email" type="email">
<label id="email-label" for="email">Email address</label>
<!-- aria-labelledby="email-label" would also work -->

aria-hidden

aria-hidden='true'는 요소를 접근성 트리에서 제거합니다 — 순수 장식 아이콘, 중복 텍스트, 읽혀서는 안 되는 화면 밖 콘텐츠에 쓰세요. 포커스 가능한 요소를 숨기지 마세요. .sr-only 패턴은 텍스트를 시각적으로 숨기면서 스크린 리더에는 유지합니다 — 말해야 하지만 보여서는 안 되는 라벨에 필수입니다.

html5
<!-- Decorative icon: hide from screen readers -->
<svg aria-hidden="true" focusable="false">
  <use href="#icon-check"></use>
</svg>

<!-- Visually hidden but still announced -->
<span class="sr-only">3 new messages</span>

<style>
  .sr-only {
    position: absolute;
    width: 1px; height: 1px;
    padding: 0; margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap; border: 0;
  }
</style>

aria-live 영역

aria-live는 업데이트가 자동으로 읽혀야 하는 영역을 표시합니다. polite는 휴식을 기다리고, assertive는 끼어듭니다. role='alert'는 assertive를 내포하며 오류 메시지의 표준입니다. aria-atomic='true'는 변경 시 전체 영역을 읽고, aria-relevant가 어떤 변경이 읽힐지 제어합니다. 아껴 쓰세요 — 과용하면 인터페이스가 시끄러워집니다.

html5
<!-- Polite: announce when screen reader is idle -->
<div aria-live="polite" id="status">Saving...</div>

<!-- Assertive: announce immediately, may interrupt -->
<div aria-live="assertive" role="alert" id="error"></div>

<script>
  function show(msg) {
    document.getElementById('status').textContent = msg;
  }
  function fail(msg) {
    document.getElementById('error').textContent = msg;
  }
</script>

포커스 관리

키보드 사용자는 Tab으로 이동하며, 포커스는 항상 보이고 논리적이어야 합니다. :focus-visible은 마우스가 아닌 키보드에만 포커스를 스타일링합니다. 모달을 열면 포커스를 안으로 옮기고, 닫으면 트리거로 돌리세요. 포커스가 숨겨진 콘텐츠로 새지 않게 Tab을 모달 안에 가두세요. tabindex > 0는 절대 금지; 요소를 포커스 가능하게는 0, 프로그래밍 방식 포커스 가능에는 -1을 쓰세요.

html5
<style>
  :focus-visible {
    outline: 3px solid #3498db;
    outline-offset: 2px;
  }
</style>

<script>
  // Move focus into a modal
  function openModal(dlg) {
    dlg.showModal();
    dlg.querySelector('input, button').focus();
  }
  // Trap focus inside the modal (simplified)
  // Restore focus to the trigger on close
  const trigger = document.activeElement;
  dlg.addEventListener('close', () => trigger.focus());
</script>

건너뛰기 링크

건너뛰기 링크는 페이지의 첫 포커스 가능 요소로, 키보드 사용자가 반복되는 내비게이션을 건너뛰고 본문으로 점프하게 합니다. 포커스될 때까지 시각적으로 숨겨집니다. 접근성에 필수입니다 — WCAG 2.1 성공 기준 2.4.1. 대상이 명확하도록 <main id='main'> 랜드마크와 짝지으세요.

html5
<body>
  <a href="#main" class="skip-link">Skip to main content</a>
  <header>...nav with 30 links...</header>
  <main id="main">...</main>
</body>

<style>
  .skip-link {
    position: absolute;
    left: -999px;
    top: 0;
    background: #000; color: #fff;
    padding: 8px 16px;
    z-index: 1000;
  }
  .skip-link:focus {
    left: 0;
  }
</style>
17

Web Components

커스텀 요소

customElements.define(name, class)가 커스텀 요소를 등록합니다. 이름에는 하이픈이 있어야 합니다. 자율 요소는 HTMLElement를 확장하고, 내장 확장은 HTMLButtonElement 같은 특정 클래스를 확장합니다(is='name'과 함께). 커스텀 요소는 웹 컴포넌트 — 재사용 가능하고 프레임워크 독립적인 UI — 의 기반입니다.

html5
<script>
  class MyButton extends HTMLElement {
    constructor() {
      super();
      this.addEventListener('click', () => {
        console.log('Custom button clicked');
      });
    }
  }
  customElements.define('my-button', MyButton);

  // Autonomous element: extends HTMLElement
  // Customized built-in: extends HTMLButtonElement
  //   <button is="my-button">
</script>

<my-button>Click me</my-button>

Shadow DOM

attachShadow({ mode: 'open' })은 요소에 붙는 캡슐화된 DOM 트리를 만듭니다. 섀도 트리 안의 스타일과 id는 밖으로 새지 않고, 페이지 스타일도 안으로 새지 않습니다(상속되는 프로퍼티 제외). :host가 호스트 요소를 타깃하고, ::slotted()가 슬롯된 자식을 스타일링합니다. mode: 'closed'는 shadowRoot 외부 접근을 막습니다 — 드묾.

html5
<script>
  class FancyCard extends HTMLElement {
    constructor() {
      super();
      const shadow = this.attachShadow({ mode: 'open' });
      shadow.innerHTML = `
        <style>
          :host { display: block; padding: 16px;
                  background: #f4f4f4; border-radius: 8px; }
          ::slotted(*) { color: #333; }
        </style>
        <div class="card">
          <slot></slot>
        </div>
      `;
    }
  }
  customElements.define('fancy-card', FancyCard);
</script>

HTML 템플릿

template 요소는 파싱되지만 복제되기 전까지 렌더링되지 않는 inert HTML을 담습니다. template.content로 접근한 뒤 cloneNode(true)와 append하세요. 템플릿은 반복 구조에 완벽하며 웹 컴포넌트의 마크업 측을 이룹니다. innerHTML과 달리 템플릿은 <tr>, <td>, <option> 등 파싱 특이점이 있는 요소를 담을 수 있습니다.

html5
<template id="row-template">
  <tr>
    <td class="name"></td>
    <td class="age"></td>
  </tr>
</template>

<script>
  const tpl = document.getElementById('row-template');
  const tbody = document.querySelector('tbody');

  function addRow(name, age) {
    const clone = tpl.content.cloneNode(true);
    clone.querySelector('.name').textContent = name;
    clone.querySelector('.age').textContent = age;
    tbody.appendChild(clone);
  }
  addRow('Ada', 36);
</script>

Slot

슬롯은 소비자가 라이트 DOM 자식을 섀도 트리의 특정 장소로 보내게 합니다. <slot name='x'>는 slot='x'인 자식을 받고, 이름 없는 <slot>은 나머지를 받습니다. 슬롯된 자식은 라이트 DOM에 머무릅니다 — 슬롯은 삽입 지점일 뿐입니다. 슬롯된 노드가 바뀔 때 반응하려면 슬롯에서 slotchange를 listen하세요.

html5
<fancy-card>
  <h2 slot="title">Card Title</h2>
  <p>Body text goes here.</p>
</fancy-card>

<!-- Inside the shadow DOM of <fancy-card>: -->
<template>
  <div class="card">
    <slot name="title"></slot>
    <div class="body"><slot></slot></div>
  </div>
</template>

라이프사이클 콜백

커스텀 요소에는 라이프사이클 콜백이 있습니다: connectedCallback(DOM에 삽입됨), disconnectedCallback(제거됨), attributeChangedCallback(observedAttributes에 나열된 속성만), adoptedCallback(새 문서로 이동됨). 생성자는 생성 시 실행됩니다 — 가볍게 유지하세요. 셋업은 connectedCallback에서, 정리는 disconnectedCallback에서. define()이 호출될 때 DOM에 이미 있던 요소는 자동 업그레이드됩니다.

html5
<script>
  class Observed extends HTMLElement {
    static get observedAttributes() {
      return ['count', 'label'];
    }
    constructor() { super(); }
    connectedCallback() {
      console.log('Added to DOM');
    }
    disconnectedCallback() {
      console.log('Removed from DOM');
    }
    attributeChangedCallback(name, oldVal, newVal) {
      console.log(name, 'changed', oldVal, '->', newVal);
    }
  }
  customElements.define('observed-el', Observed);
</script>
18

오프라인 애플리케이션

Service Worker 등록

서비스 워커는 페이지와 별개로 브라우저가 백그라운드에서 실행하는 스크립트로, 오프라인 지원, 푸시 알림, 백그라운드 동기화를 가능하게 합니다. 페이지 스크립트에서 등록하세요; SW 파일은 HTTPS(또는 localhost)로 서빙되어야 하고 스코프는 기본적으로 자기 디렉터리입니다. 설치되면 fetch 이벤트로 페이지 로드를 제어합니다.

html5
<script>
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker
        .register('/sw.js', { scope: '/' })
        .then((reg) => console.log('SW registered', reg.scope))
        .catch((err) => console.error('SW failed', err));
    });
  }
</script>

Cache API

Cache API는 Request/Response 쌍을 세션을 넘어 저장합니다. install 이벤트에서 핵심 자산을 미리 캐시하세요. fetch 이벤트에서 캐시 우선으로 응답하고 네트워크로 폴백합니다(cache-first 전략). 다른 전략: network-first, stale-while-revalidate, cache-only, network-only. 오래된 항목 무효화에는 캐시 이름을 올리세요.

html5
// sw.js
const CACHE = 'app-v1';
const ASSETS = ['/', '/styles.css', '/app.js', '/offline.html'];

self.addEventListener('install', (e) => {
  e.waitUntil(
    caches.open(CACHE).then((c) => c.addAll(ASSETS))
  );
});

self.addEventListener('fetch', (e) => {
  e.respondWith(
    caches.match(e.request).then((r) => r || fetch(e.request))
  );
});

오프라인 폴백

오프라인 폴백이 있는 network-first 전략은 네트워크를 시도하고, 그다음 캐시, 그다음 일반 오프라인 페이지로 갑니다. activate 이벤트는 install이 완료된 뒤 실행되며 오래된 캐시를 삭제하는 적합한 자리입니다 — 아니면 쌓입니다. activate 안에서 self.clients.claim()으로 클라이언트가 기존 탭을 즉시 장악하게 할 수 있습니다.

html5
// sw.js
self.addEventListener('fetch', (e) => {
  e.respondWith(
    fetch(e.request).catch(() =>
      caches.match(e.request).then((r) =>
        r || caches.match('/offline.html')
      )
    )
  );
});

// Activate event: clean up old caches
self.addEventListener('activate', (e) => {
  e.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(
        keys.filter((k) => k !== 'app-v1')
            .map((k) => caches.delete(k))
      )
    )
  );
});

웹 앱 매니페스트

웹 앱 매니페스트는 홈 화면에 설치될 때 앱이 어떻게 보일지 기술하는 JSON 파일입니다. name/short_name, icons, start_url, display(standalone, fullscreen, minimal-ui, browser)가 핵심 필드입니다. 서비스 워커와 결합하면 매니페스트가 앱을 설치 가능하게 만듭니다(PWA). theme_color가 OS UI 크롬에 영향을 줍니다.

html5
<!-- index.html -->
<link rel="manifest" href="manifest.json">

<!-- manifest.json -->
{
  "name": "My App",
  "short_name": "App",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#3498db",
  "icons": [
    { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
  ]
}

백그라운드 동기화

백그라운드 동기화(navigator.serviceWorker.ready.then(r => r.sync.register('tag'))로 등록)는 연결이 생길 때까지 작업을 미룹니다. 네트워크가 돌아오면 — 페이지가 닫혀 있어도 — 브라우저가 서비스 워커에서 sync 이벤트를 발생시킵니다. 대기 중인 폼 제출, 메시지, 분석 데이터 전송에 쓰세요. tag가 동기를 식별하며 중복은 합쳐집니다.

html5
// sw.js
self.addEventListener('sync', (e) => {
  if (e.tag === 'send-messages') {
    e.waitUntil(sendQueuedMessages());
  }
});

async function sendQueuedMessages() {
  const queue = await getQueue();
  for (const msg of queue) {
    try { await fetch('/api/send', { method: 'POST', body: msg }); }
    catch (e) { throw e; }   // retry later
  }
}
19

SEO 모범 사례

Title & 메타 설명

title(약 60자 이하)이 가장 중요한 온페이지 SEO 신호이며 검색 결과의 헤드라인으로 나타납니다. 메타 설명(약 160자 이하)은 스니펫 텍스트입니다 — 순위에는 영향이 없지만 클릭률에는 영향을 줍니다. 페이지마다 하나의 title을 쓰고, 주요 키워드를 포함하고, 클릭하고 싶게 만드세요. canonical이 중복 콘텐츠 문제를 막습니다.

html5
<head>
  <title>HTML5 Cheatsheet - Semantic Elements & APIs</title>
  <meta name="description"
        content="A quick reference to HTML5 semantic elements,
                 form types, and browser APIs with examples.">
  <meta name="robots" content="index, follow">
  <link rel="canonical" href="https://example.com/html5">
</head>

Open Graph & Twitter Cards

Open Graph 태그는 Facebook, LinkedIn, Slack, 대부분의 소셜 플랫폼에서 공유될 때 페이지가 어떻게 보이는지 제어합니다. og:image는 1200x630px이어야 합니다. Twitter Cards는 twitter: 접두사가 붙은 비슷한 집합을 씁니다(또는 OG로 폴백). 이것들이 없으면 공유가 무작위 또는 미리보기 없는 이미지를 얻어 클릭률이 크게 줄어듭니다.

html5
<head>
  <!-- Open Graph (Facebook, LinkedIn, etc.) -->
  <meta property="og:title" content="HTML5 Cheatsheet">
  <meta property="og:description" content="Quick HTML5 reference.">
  <meta property="og:image" content="https://example.com/og.png">
  <meta property="og:url" content="https://example.com/html5">
  <meta property="og:type" content="article">

  <!-- Twitter Card -->
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:site" content="@example">
</head>

Canonical & hreflang

rel='canonical'은 여러 URL이 비슷한 콘텐츠를 가질 때(인쇄, 정렬, 쿼리 파라미터) 어느 URL이 대표본인지 검색 엔진에 알립니다 — 중복 콘텐츠 페널티를 막습니다. hreflang은 번역되거나 지역별 버전을 가리켜 Google이 올바른 것을 서빙하게 합니다. 매칭되지 않는 로케일을 위한 x-default를 항상 포함하세요. 둘 다 절대 URL이어야 합니다.

html5
<head>
  <!-- Canonical: the master URL for duplicate content -->
  <link rel="canonical" href="https://example.com/article">

  <!-- hreflang: language/region alternatives -->
  <link rel="alternate" hreflang="en" href="https://example.com/en/article">
  <link rel="alternate" hreflang="es" href="https://example.com/es/article">
  <link rel="alternate" hreflang="x-default" href="https://example.com/article">
</head>

구조화 데이터 (JSON-LD)

JSON-LD 구조화 데이터는 기계 판독 형식(schema.org 어휘)으로 페이지를 기술하며 검색의 리치 결과를 가능하게 합니다: 기사 캐러셀, 브레드크럼, FAQ, 리뷰, 이벤트, 제품. <script type='application/ld+json'>에 넣으세요. Google의 Rich Results Test로 검증하세요. 순위를 직접 올리지는 않지만 결과의 모양을 개선합니다.

html5
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "HTML5 Cheatsheet",
  "author": { "@type": "Person", "name": "Ada" },
  "datePublished": "2024-07-04",
  "image": "https://example.com/cover.png",
  "publisher": {
    "@type": "Organization",
    "name": "Example"
  }
}
</script>

시맨틱 제목

검색 엔진과 스크린 리더는 제목으로 페이지 아웃라인을 이해합니다. h1(페이지 제목)을 하나 쓰고, 주요 섹션은 h2, 하위 섹션은 h3 — 수준을 건너뛰지 마세요(h2에서 h4로 바로 가지 않음). 크기 때문에 제목을 고르지 마세요; 스타일링은 CSS로 하세요. 논리적인 제목 계층이 SEO와 접근성을 모두 개선합니다.

html5
<article>
  <h1>Article Title (only one h1 per page)</h1>
  <p>Intro paragraph.</p>

  <section>
    <h2>First major section</h2>
    <p>Content...</p>
    <h3>Subsection</h3>
    <p>Detail...</p>
  </section>

  <section>
    <h2>Second major section</h2>
    <p>Content...</p>
  </section>
</article>
20

성능 최적화

preload

rel='preload'는 브라우저에게 현재 페이지가 필요로 할 높은 우선순위 리소스를, 보통 발견되기 전에 미리 가져오라고 알립니다. 브라우저가 올바른 우선순위와 CSP를 적용하도록 항상 as(font, style, script, image, fetch 등)를 지정하세요. 폰트에는 crossorigin이 필요합니다. preload는 진짜 핵심 리소스에만 쓰세요 — 과용은 대역폭을 낭비합니다.

html5
<head>
  <!-- Preload critical resources for the current page -->
  <link rel="preload" href="/fonts/main.woff2"
        as="font" type="font/woff2" crossorigin>
  <link rel="preload" href="/css/critical.css" as="style">
  <link rel="preload" href="/js/app.js" as="script">

  <!-- Preload a hero image -->
  <link rel="preload" href="/hero.webp" as="image">
</head>

prefetch & preconnect

preconnect는 어떤 오리진에 대한 DNS, TCP, TLS를 미리 완료해 실제 요청 시 약 100-300ms를 아낍니다 — 핵심 서드파티 도메인에 쓰세요. dns-prefetch는 더 가벼운 버전입니다(DNS만). prefetch는 다음 탐색 가능성이 있는 낮은 우선순위 리소스를 미리 가져옵니다. 아껴 쓰세요: preconnect가 많으면 소켓을 낭비하고 prefetch된 리소스는 쓰이지 않을 수 있습니다.

html5
<head>
  <!-- preconnect: early handshake to a third-party origin -->
  <link rel="preconnect" href="https://cdn.example.com">
  <link rel="preconnect" href="https://api.example.com" crossorigin>

  <!-- dns-prefetch: just DNS lookup, lighter -->
  <link rel="dns-prefetch" href="https://cdn.example.com">

  <!-- prefetch: fetch a resource for the NEXT navigation -->
  <link rel="prefetch" href="/next-page.html">
</head>

지연 로딩

img와 iframe의 loading='lazy'는 요소가 뷰포트에 가까워질 때까지 로드를 미룹니다 — 초기 렌더의 대역폭과 CPU를 아낍니다. decoding='async'는 이미지 디코드가 메인 스레드를 막지 않게 합니다. 레이아웃 시프트를 피하려면 항상 width/height를 설정하세요. loading='eager'(기본값)와 fetchpriority='high'는 화면 위쪽 히어로 이미지에만 쓰세요. 모든 모던 브라우저에서 지원됩니다.

html5
<!-- Native lazy loading (no JS needed) -->
<img src="photo.jpg" loading="lazy" decoding="async" alt="...">
<iframe src="embed.html" loading="lazy"></iframe>

<!-- Eager (default) loads immediately -->
<img src="hero.jpg" loading="eager" fetchpriority="high" alt="Hero">

<!-- Defer non-critical images until they near the viewport -->
<img src="below-fold.jpg" loading="lazy" width="800" height="600" alt="">

defer & async

일반 <script>는 다운로드와 실행 동안 HTML 파싱을 막습니다. async는 병렬로 다운로드해 준비되는 대로 실행합니다 — 순서가 무관한 독립 스크립트(분석, 광고)에 쓰세요. defer는 병렬로 다운로드하지만 문서가 파싱된 뒤 순서대로 실행을 기다립니다 — DOM에 의존하는 메인 앱 스크립트에 쓰세요. defer 스크립트는 DOMContentLoaded 전에 실행됩니다.

html5
<head>
  <!-- async: download in parallel, run ASAP (order not guaranteed) -->
  <script src="analytics.js" async></script>

  <!-- defer: download in parallel, run after parse, in order -->
  <script src="app.js" defer></script>
  <script src="page.js" defer></script>

  <!-- Classic: block parsing to download and run -->
  <script src="blocking.js"></script>
</head>

리소스 힌트 요약

preload(현재 페이지), prefetch(다음 페이지), preconnect(오리진 핸드셰이크), dns-prefetch(DNS만)가 핵심 리소스 힌트입니다. prerender는 Speculation Rules API가 대체하며 폐기되었고, 이 API는 즉시 탐색을 위해 페이지를 완전히 사전 렌더링할 수 있습니다. 힌트는 실제 사용자 행동에 근거해 적용하세요 — 과한 힌트는 데이터를 낭비하고 성능을 해칠 수 있습니다.

html5
<head>
  <link rel="preload"    href="/critical.woff2" as="font" crossorigin>
  <link rel="preconnect" href="https://cdn.example.com">
  <link rel="dns-prefetch" href="https://cdn.example.com">
  <link rel="prefetch"   href="/next-page.html">

  <!-- Speculation Rules API (Chrome) -->
  <script type="speculationrules">
  { "prerender": [{ "where": { "href_matches": "/next/*" } }] }
  </script>
</head>

임계 렌더링

화면 위쪽 콘텐츠의 임계 CSS 인라이닝은 렌더 차단 요청을 없애 First Contentful Paint를 개선합니다. 나머지는 preload+swap으로 로드하세요. content-visibility: auto는 브라우저가 화면 밖 섹션의 렌더링을 건너뛰게 해 긴 페이지의 스크롤 성능을 크게 개선합니다 — 스크롤바 떨림을 피하려 공간을 예약하는 contain-intrinsic-size와 짝지으세요.

html5
<head>
  <!-- Inline critical CSS for above-the-fold -->
  <style>
    body { margin: 0; font: system-ui; }
    .hero { height: 60vh; background: #3498db; }
  </style>

  <!-- Load the rest asynchronously -->
  <link rel="preload" href="/full.css" as="style" onload="this.rel='stylesheet'">
  <noscript><link rel="stylesheet" href="/full.css"></noscript>
</head>
<body>
  <!-- Use content-visibility to skip off-screen rendering -->
  <section style="content-visibility: auto; contain-intrinsic-size: 500px;">
    Heavy content here
  </section>
</body>

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.