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>

Navigation 要素

nav は主要なナビゲーションブロックのために確保されています。リンクのリストすべてに nav が要るわけではなく — サイトナビゲーションにとって重要なグループだけです。複数の nav 要素を区別するには aria-label を使いましょう(メインとパンくずなど)。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 はページの支配的なコンテンツを包み、ページに 1 回だけ現れるべきです('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 は主要コンテンツに傍らで関連するコンテンツを表します — サイドバー、引き出し引用、広告など。どちらも文書のアウトラインを改善します。section にアクセシブルな名前を与えるには 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 のような入力タイプを追加しました。ブラウザがネイティブのバリデーションと専用 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 属性経由で入力へオートコンプリートの候補を提供します。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 プロパティと、寄与した入力を参照する for 属性を持ちます。フォーム関連要素であるため、その value はフォームと共に送信されます。ライブ計算機に最適です。

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 属性は、input、fieldset、button を id でフォームに関連付けます。要素がフォームの中にネストされていなくても。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 は入力内にヒントを表示し、フォーカスで消えます — label の代替ではありません。autofocus はページロード時に要素へフォーカスします(控えめに、1 ページに 1 つ)。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 属性がフィールドを必須とし、空のまま送信すると、ブラウザが送信をブロックしてエラーの吹き出しを表示します。すべてのテキスト、数値、checkbox、radio、file、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 属性が失敗時にユーザーへヒントを与えます。type=email/url では暗黙にアンカリングされますが、テキスト系入力では明示的です。

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 が数値・日付入力の下限と上限を定義します。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 がテキスト入力と 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>

Constraint Validation API

Constraint Validation 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 で検証するときに有用です。送信ボタンの 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 サイズではない)。retina ディスプレイでの鮮明な描画には、バッファを 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 引数では最初の 4 つがソース長方形(切り出し)、最後の 4 つが宛先長方形です。描画の前には 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 の offset でカラーストップを加えます。標準的な色文字列を必ず渡しましょう。形式の不一致(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 は、表示サイズのための width/height と座標系のための viewBox を持つ svg 要素を使います。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 = 三次ベジェ、Q = 二次ベジェ、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 と 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

Audio と Video

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

Geolocation

getCurrentPosition

getCurrentPosition は成功コールバック、省略可能なエラーコールバック、オプションオブジェクトを受け取ります。position オブジェクトは coords.latitude、longitude、accuracy を、そして利用可能なときは altitude、heading、speed を公開します。Geolocation は 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>

Position のオプション

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 オプションより長くかかったことです。3 ケースすべてを優雅に処理しましょう。

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 しましょう。geolocation、notifications、camera、microphone などに対応しています。

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

Web Storage

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 データの保存

Web Storage は文字列しか保存しないため、オブジェクトや配列には 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 イベント

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

オブジェクトストアはテーブルのようなもので、各レコードがキーと値(structured clone 可能な任意のオブジェクト)を持ちます。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() は upsert します。トランザクションはすべてのリクエストが完了すると自動コミットされるため、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() でレコードを 1 つずつ反復できます — メモリに収まらない大きな dataset に最適です。進めるには 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

Drag and Drop 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>

Drag イベント

ドロップを受け付けるには、dragover と drop の両方で MUST で 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 で解除します。OS からファイルをドラッグすると dataTransfer.files が FileList を与えるため、ドラッグアンドドロップのアップロードが可能になります。drop イベントが発火しないため、dragover では必ず preventDefault しましょう。ネストした要素があるなら 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 内で描画済みである必要があるため、作成し、append し、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 Workers

Worker の基本

new Worker(url) がスクリプトファイルを実行するバックグラウンドスレッドを生み出します。通信は postMessage と onmessage 経由で、データはスレッド間で(structured clone により)コピーされます。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') が他のスクリプトを同期的に Worker へロードします。各 Worker は独自の isolate で動きます。

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) がデータを送り、structured clone でコピーします。第 2 引数に ArrayBuffer、MessagePort、ImageBitmap の配列を渡すと、コピーではなく所有権を「転送」します — 大きなバッファでははるかに速いですが、元のものは送信側スレッドで使えなくなります。

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 オブジェクト

Transferable オブジェクト(ArrayBuffer、MessagePort、ImageBitmap、OffscreenCanvas)はコピーなしでスレッド間を移動します。transferControlToOffscreen が canvas を Worker へ引き渡し、Worker が独立に描画できます — メインスレッドが忙しい間の滑らかなアニメーションに最適です。メインスレッドは転送されたオブジェクトへのアクセスを失います。

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 は、同じオリジンの複数のタブで共有される単一の Worker です。各接続は 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 ルーター:内部リンクのクリックを横取りし、pushState で URL を更新し、新しいビューを描画します。戻る/進むが機能するよう 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' が 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 経由で略語を展開し(ホバーツールチップ)、スクリーンリーダーを助けます。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

Custom Elements

customElements.define(name, class) がカスタム要素を登録します。名前にはハイフンが必要です。自律的な要素には HTMLElement を継承し、組み込みを拡張するには HTMLButtonElement のような特定のクラスを(is='name' と共に)継承します。カスタム要素は Web Components の基礎です — 再利用可能でフレームワークに依存しない 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 要素は、パースはされるが複製されるまで描画されない不活性な HTML を保持します。内容には template.content 経由でアクセスし、cloneNode(true) と append を行いましょう。テンプレートは繰り返し構造に最適で、Web Components のマークアップ側を担います。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

Slot により、利用者がライト DOM の子をシャドウツリーの特定の場所へ渡せます。<slot name='x'> が slot='x' を持つ子を受け取り、名前のない <slot> が残りを受け取ります。スロットされた子はライト DOM に留まり、slot は単なる挿入ポイントです。スロットされたノードが変わったときに反応するには、slot の 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(新しい文書へ移動)。constructor は作成時に動きます — 軽く保ちましょう。セットアップは 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 の登録

service worker は、ページと別にブラウザがバックグラウンドで動かすスクリプトで、オフライン対応、プッシュ通知、バックグラウンド同期を可能にします。ページのスクリプトから登録しましょう。SW ファイルは HTTPS(または localhost)で提供される必要があり、その scope はデフォルトで自身のディレクトリです。インストールされると、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 イベントでは、まずキャッシュから応答し、ネットワークへフォールバックします(キャッシュファースト戦略)。他の戦略:ネットワークファースト、stale-while-revalidate、キャッシュのみ、ネットワークのみ。古いエントリを無効化するにはキャッシュ名を上げましょう。

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))
  );
});

オフラインフォールバック

オフラインフォールバック付きのネットワークファースト戦略は、ネットワークを試し、次にキャッシュ、最後に汎用のオフラインページを試します。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))
      )
    )
  );
});

Web App Manifest

Web アプリのマニフェストは、ホーム画面にインストールされたときのアプリの見た目を記述する JSON ファイルです。name/short_name、icons、start_url、display(standalone、fullscreen、minimal-ui、browser)が主要なフィールドです。service worker と組み合わせると、マニフェストによりアプリがインストール可能になります(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" }
  ]
}

Background Sync

Background Sync(navigator.serviceWorker.ready.then(r => r.sync.register('tag')) で登録)は、ユーザーが接続可能になるまで作業を先送りします。ネットワークが戻ると、ページが閉じられていても、ブラウザが service worker 内で 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 と Meta Description

title(約 60 文字以下)が最重要のページ内 SEO シグナルで、検索結果の見出しとして現れます。meta description(約 160 文字以下)がスニペットのテキストです — ランキングには影響しませんが、クリックスルーに影響します。ページごとに 1 つのタイトル、主要キーワードを含め、魅力あるものにしましょう。重複コンテンツ問題の回避には 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>

セマンティックな見出し

検索エンジンとスクリーンリーダーは、ページのアウトラインを理解するために見出しを使います。1 つの 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 が、即時ナビゲーションのためにページを完全に事前描画できます。ヒントは実際のユーザー行動に基づいて適用しましょう — ヒントのしすぎはデータを浪費し、パフォーマンスを損なうことがあります。

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.