시맨틱 요소
문서 구조
HTML5는 브라우저와 개발자 모두에게 의미를 전달하는 시맨틱 요소를 도입했습니다. header, nav, main, article, aside, footer가 문서 구조를 정의합니다. DOCTYPE html이 표준 모드를 트리거하고, lang이 접근성과 SEO를 개선하며, 올바른 인코딩에는 charset UTF-8이 필요합니다.
<!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 같은 섹셔닝 요소 안에서도 사용할 수 있습니다.
<header>
<h1>Site Title</h1>
<p>Tagline</p>
</header>
<footer>
<nav>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</nav>
<small>© 2024 Example</small>
</footer>내비게이션 요소
nav는 주요 내비게이션 블록을 위한 것입니다. 모든 링크 목록이 nav를 필요로 하는 것은 아닙니다 — 사이트 내비게이션에서 중요한 그룹만 해당됩니다. 여러 nav 요소를 구분하려면 aria-label을 쓰세요(예: 메인 vs 브레드크럼). aria-current는 현재 페이지를 나타냅니다.
<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은 주제가 관련된 콘텐츠를 묶으며 항상 제목을 동반합니다.
<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를 쓰세요.
<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 같은 독립적 콘텐츠에도 쓰입니다.
<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>폼 개선
새 입력 타입
HTML5는 email, url, tel, date, time, color, range, number, month, week, datetime-local 같은 input 타입을 추가했습니다. 브라우저가 네이티브 검증과 전용 UI(데이트 피커, 컬러 피커)를 제공합니다. type=email/url은 폼 제출 시 자동 형식 검증을 트리거합니다.
<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는 지원하지 않는 브라우저에서 일반 텍스트 입력으로 우아하게 저하됩니다.
<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 속성을 갖습니다. 폼 연계 요소이므로 값이 폼과 함께 제출됩니다. 실시간 계산기에 좋습니다.
<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는 읽기 전용이며 진행 표시용이 아닙니다.
<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 속성은 포함된 모든 컨트롤을 한 번에 비활성화합니다.
<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은 툴팁을 제공하지만 접근 가능한 라벨을 대체해서는 안 됩니다.
<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>폼 검증
required 속성
불리언 required 속성은 필드를 필수로 표시합니다; 비어 있으면 브라우저가 제출을 차단하고 오류 말풍선을 보여줍니다. 모든 텍스트, 숫자, 체크박스, 라디오, 파일, select 컨트롤에 동작합니다. 시각적 피드백으로 :invalid와 :valid CSS 의사 클래스와 짝지으세요.
<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에는 명시적입니다.
<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'는 임의의 소수를 허용합니다. 브라우저는 제출 시 범위 밖 값을 거부하고 스피너 클릭을 조정합니다.
<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는 한도를 넘는 입력을 하드 차단해 타이핑 자체를 막습니다.
<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도 보여줍니다.
<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는 그 버튼의 제출에만 검증을 건너뜁니다(예: 불완전한 데이터를 허용하는 '임시 저장'). 둘 다 폼은 여전히 제출합니다.
<!-- 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>Canvas 그리기
Canvas 요소 & 2D 컨텍스트
canvas는 비트맵 드로잉 표면입니다. getContext('2d')가 2D 렌더링 컨텍스트를, 'webgl'은 3D 컨텍스트를 반환합니다. width/height 속성이 드로잉 버퍼 크기를 정합니다(CSS 크기 아님). 레티나에서 선명하게 렌더링하려면 버퍼를 devicePixelRatio만큼 스케일하세요. 폴백 콘텐츠는 태그 사이에 둡니다.
<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가 선 두께에 영향을 주며 경로 가장자리를 중심으로 합니다.
<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), 사각형도 경로에 추가할 수 있습니다.
<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가 렌더링된 너비를 반환합니다.
<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를 기다리세요 — 아니면 이미지가 나타나지 않을 수 있습니다.
<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에 할당하세요.
<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>인라인 SVG
SVG 요소 기본
인라인 SVG는 svg 요소를 쓰며 width/height가 표시 크기, viewBox가 좌표계입니다. xmlns는 SVG를 독립적으로 쓸 때 필수이고 인라인에서는 선택입니다. SVG는 벡터 기반입니다: 어떤 크기에서도 선명하게 스케일되며 일반 HTML처럼 검색과 CSS 스타일링이 됩니다.
<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로도 설정할 수 있습니다.
<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를 씁니다.
<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에 그린 텍스트와 다릅니다.
<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는 패 턴, 클립 경로, 재사용 심볼도 담습니다.
<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 접근이 불가합니다.
<!-- 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>오디오 & 비디오
Video 요소
video는 플러그인 없이 비디오를 삽입합니다. controls가 네이티브 UI를 보여주고, poster가 재생 전 썸네일입니다. 여러 source 요소로 브라우저가 첫 지원 코덱을 고릅니다. 태그 사이의 폴백 텍스트는 미지원 브라우저에서 표시됩니다. 레이아웃 시프트를 피하려면 항상 width/height를 포함하세요.
<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가 아니면 브라우저가 차단할 수 있습니다.
<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를 만능 폴백으로 두세요. 태그 안의 다운로드 링크가 우아한 폴백입니다.
<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도 개선합니다.
<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는 피하세요.
<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를 숨기고 버튼을 이 메서드들에 연결해 커스텀 플레이어를 만드세요.
<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>지리 위치
getCurrentPosition
getCurrentPosition은 성공 콜백과 선택적 오류 콜백, 옵션 객체를 받습니다. position 객체는 coords.latitude, longitude, accuracy와 — 사용 가능하면 — altitude, heading, speed를 노출합니다. 지리 위치는 HTTPS(또는 localhost)에서만 동작하며 사용자 권한을 요청합니다.
<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 호출을 피합니다.
<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에 전달해 업데이트를 멈추세요. 내비게이션 앱에 필수입니다. 배터리를 신경 쓰세요 — 합리적인 업데이트 간격을 쓰고 필요 없을 때 감시를 멈추세요.
<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 옵션보다 오래 걸렸다는 뜻입니다. 세 사례를 모두 우아하게 처리하세요.
<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하세요. 지리 위치, 알림, 카메라, 마이크 등을 지원합니다.
<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>웹 스토리지
localStorage 기본
localStorage는 만료 없이 문자열 키/값 쌍을 저장합니다; 데이터는 탭과 세션을 넘어 유지됩니다. 값은 문자열이므로 숫자와 불리언은 자동 변환됩니다. 한도는 오리진당 약 5MB입니다. 저장소는 동기식이며 메인 스레드를 막으니 큰 쓰기를 피하세요. 프라이빗 모드에서 접근 시 예외가 날 수 있으니 try/catch로 감싸세요.
<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 토큰 같은 일시적 데이터에 유용합니다. 같은 오리진이라도 데이터는 탭 간 공유되지 않습니다.
<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') — 스키마 변경이 옛 데이터를 깨지 않게.
<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를 운반합니다. 탭 간 로그아웃, 테마 변경, 실시간 업데이트 동기화에 쓰세요.
<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하세요.
<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>IndexedDB
데이터베이스 열기
indexedDB.open(name, version)이 데이터베이스를 열거나 만듭니다. onupgradeneeded는 버전이 올라가거나 DB가 처음 만들어질 때 발생합니다 — 객체 스토어와 인덱스를 만들거나 바꿀 수 있는 유일한 곳입니다. 스키마를 바꿀 때마다 버전을 올리세요. 스토어에는 keyPath(키로 쓰일 프로퍼티)나 자동 증가 키가 필요합니다.
<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가 그 필드의 중복을 막습니다.
<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하세요. 트랜잭션은 짧게 유지하세요 — 같은 스토어의 다른 트랜잭션을 막습니다.
<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에 있습니다.
<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)가 인덱스 쿼리의 범위를 정합니다 — 접두사나 범위 검색에 유용합니다.
<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>드래그 앤 드롭 API
드래그 가능하게 만들기
요소에 draggable='true'를 설정하면 드래그 가능해집니다. dragstart 이벤트는 드래그 시작 시 발생하며, dataTransfer.setData로 드롭 대상에 전달할 데이터를 포장하세요. effectAllowed(copy, move, link, all, none)가 의도한 연산을 힌트합니다. dragend는 드롭 여부와 무관하게 드래그가 끝나면 발생합니다.
<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 이벤트는 드래그 중 소스에서 계속 발생합니다.
<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 이벤트로 제한합니다.
<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 카운터를 쓰세요.
<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 뒤에 제거하세요. 오프셋이 커서를 이미지 왼쪽 위 기준으로 위치시킵니다. 이미지를 넘기지 않으면 브라우저가 드래그된 요소를 스크린샷합니다.
<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>Web Worker
Worker 기본
new Worker(url)이 스크립트 파일을 실행하는 백그라운드 스레드를 만듭니다. 통신은 postMessage와 onmessage이며, 데이터가 스레드 사이에 복사됩니다(구조화 클론). Worker는 DOM, window, document를 만질 수 없지만 — fetch, IndexedDB, setTimeout은 쓸 수 있습니다. UI가 반응성을 유지하도록 무거운 계산에 쓰세요.
<!-- 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')가 다른 스크립트를 동기로 워커에 로드합니다. 각 워커는 자신의 격리에서 실행됩니다.
// 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합니다 — 큰 버퍼에 훨씬 빠르지만 원본이 전송 스레드에서 쓸 수 없게 됩니다.
<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를 워커에 넘기고, 워커가 이를 독립적으로 렌더링합니다 — 메인 스레드가 바쁠 때도 부드러운 애니메이션에 좋습니다. 메인 스레드는 이전된 객체 접근을 잃습니다.
<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에서 지원되지 않고 특이점이 있으니 — 의존하기 전에 테스트하세요.
<!-- 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();
};WebSocket
연결 열기
new WebSocket(url)이 지속적인 양방향 연결을 엽니다. 프로덕션에서는 wss://(TLS)를 쓰세요 — ws://는 평문이며 HTTPS 페이지에서 차단됩니다. readyState는 CONNECTING(0) → OPEN(1) → CLOSING(2) → CLOSED(3)으로 갑니다. open, message, error, close 이벤트를 listen하세요.
<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을 확인하세요. 프로토콜은 풀 듀플렉스입니다 — 어느 쪽이든 언제든 보낼 수 있습니다.
<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를 고르세요. 양쪽이 모양에 동의하도록 메시지 스키마를 정의하세요.
<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입니다.
<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 시 재연결하되 재시도 간격에 상한을 두어 서버를 때리지 않게 하세요. 성공적으로 연결되면 재시도 카운터를 초기화하세요.
<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>History API
pushState
pushState(state, title, url)는 세션 히스토리에 새 항목을 추가하고 주소창을 갱신하며 페이지를 리로드하지 않습니다 — 클라이언트 측 라우팅의 핵심입니다. URL은 같은 오리진이어야 하며 아니면 pushState가 예외를 냅니다. title 인수는 현재 브라우저가 무시합니다. state 객체는 직렬화 가능하며 history.state로 회수됩니다.
<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이나 상태를 갱신할 때 쓰세요 — 예: 사용자가 '뒤로 가기'로 되돌리길 원치 않는 필터 적용 뒤.
<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 핸들러 양쪽에서 렌더 함수를 호출해 모든 탐색이 뷰를 갱신하게 합니다.
<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하면 아무것도 하지 않습니다.
<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는 건너뛰세요. 실제 프레임워크는 중첩 라우트, 파라미터, 가드, 스크롤 복원을 추가합니다.
<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>인라인 시맨틱 요소
time 요소
time은 특정 날짜, 시간, 지속 기간을 나타냅니다. 기계 판독 값은 datetime 속성에(YYYY-MM-DD, HH:MM, 또는 시간대가 있는 완전한 ISO 8601), 사람용 텍스트는 콘텐츠로 둡니다. 검색 엔진과 캘린더 앱이 datetime으로 이벤트를 추출합니다. datetime이 없으면 콘텐츠 자체가 유효한 날짜 문자열이어야 합니다.
<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 안에서도 유용합니다.
<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, 고급 설 정, 콘텐츠의 점진적 공개에 좋습니다.
<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이 오버레이를 스타일링합니다.
<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로 링크할 수 있습니다.
<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>반응형 디자인
Meta Viewport
viewport 메타 태그는 모바일 브라 우저에게 기기 너비를 레이아웃 뷰포트로 쓰고 스케일 1에서 시작하라고 알립니다. 없으면 폰이 980px 폭인 척합니다. initial-scale=1이 로드 시 줌을 막습니다. viewport-fit=cover는 env(safe-area-inset-*)과 함께 노치 영역을 쓰게 합니다. user-scalable=no는 피하세요 — 접근성을 깨뜨립니다.
<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 텍스트를 제공합니다. 리사이즈만이 아니라 브레이크포인트마다 이미지를 완전히 자르거나 바꿔야 할 때 쓰세요.
<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가 필요 없습니다. 같은 이미지가 다른 해상도만 필요할 때 쓰세요.
<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는 짧은/긴 쪽을 씁니다.
<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'와 결합하면 가장 효율적인 이미지 전달 방법입니다.
<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. -->접근성 (ARIA)
ARIA 역할
ARIA 역할은 보조 기술에 요소의 기능을 알리지만, ARIA의 첫 규칙은 이것입니다: 네이티브 HTML 요소가 있으면 쓰지 마세요. header, nav, main, article, footer는 이미 banner, navigation, main, article, contentinfo 역할을 노출합니다. ARIA는 네이티브 등가물이 없는 커스텀 위젯(tab, dialog, slider, menu)에 쓰고, 역할은 키보드 지원과 짝지으세요.
<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는 라벨 뒤에 읽히는 힌트 텍스트를 가리킵니다.
<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 패턴은 텍스트를 시각적으로 숨기면서 스크린 리더에는 유지합니다 — 말해야 하지만 보여서는 안 되는 라벨에 필수입니다.
<!-- 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가 어떤 변경이 읽힐지 제어합니다. 아껴 쓰세요 — 과용하면 인터페이스가 시끄러워집니다.
<!-- 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을 쓰세요.
<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'> 랜드마크와 짝지으세요.