最適化と注意点

ネットワーク最適化のチェックリスト。HTTP/2/3、圧縮、CDN、画像、Resource Hints、Early Hints、CSP まで。

パフォーマンスの主軸

  1. 遅延(latency)を減らす — 物理的に近い CDN、HTTP/3、0-RTT
  2. 転送量を減らす — 圧縮、画像最適化、不要 JS を削る
  3. 並列化する — HTTP/2 多重化、preload、prefetch
  4. キャッシュする — ブラウザ・CDN・SW

HTTP/2 / HTTP/3 を使う

圧縮

多くの CDN / Cloudflare Pages / Vercel は自動で Brotli

画像最適化

<picture>
  <source type="image/avif" srcset="hero.avif" />
  <source type="image/webp" srcset="hero.webp" />
  <img src="hero.jpg" alt="..." loading="lazy" decoding="async" />
</picture>

レスポンシブ画像

<img
  src="hero-800.jpg"
  srcset="hero-400.jpg 400w, hero-800.jpg 800w, hero-1600.jpg 1600w"
  sizes="(max-width: 600px) 100vw, 50vw"
  alt="..."
/>

Resource Hints

ブラウザに「これ後で要るよ」と教える hint タグ。

<link rel="preconnect" href="https://api.example.com" />
<link rel="preload" href="/fonts/Inter.woff2" as="font" type="font/woff2" crossorigin />
<link rel="prefetch" href="/next-page.html" />

Early Hints (103)

サーバーが本レスポンスより先103 Early Hints を返して、preconnect / preload を伝える。 TTFB 待ち中に並列ロード開始できる。Cloudflare / Fastly が対応。

HTTP/2 Server Push(廃止)

以前推奨された Server Push は非推奨・廃止傾向。Early Hints が後継。

Critical CSS

ファーストビューに必要な CSS だけHTML にインライン、残りは非同期。

<style>/* critical CSS */</style>
<link rel="preload" href="/all.css" as="style" onload="this.rel='stylesheet'" />

Web Font 最適化

CDN の活用

Compression Streams API

ブラウザでもgzip / deflate / deflate-rawの圧縮・展開ができる:

// 圧縮
const compressed = await new Response(
  new Blob([data]).stream().pipeThrough(new CompressionStream("gzip"))
).blob()

// 展開
const decompressed = await new Response(
  blob.stream().pipeThrough(new DecompressionStream("gzip"))
).text()

セキュリティヘッダー

Hono / Fastify / Express の secure-headers ミドルウェア

全部一気にセットしてくれる。securityheaders.com でスコア確認。

Rate Limiting

計測

web-vitals ライブラリ

npm install web-vitals
import { onLCP, onINP, onCLS } from "web-vitals"

onLCP(console.log)
onINP(console.log)
onCLS(console.log)

失敗のリトライとサーキットブレーカー

大容量転送のコツ

よくある落とし穴

判断ガイド

症状対策
初回が遅いCritical CSS / preload / Early Hints / CDN
毎回サーバが重いキャッシュ / SWR / CDN
画像が遅いAVIF / lazy-loading / レスポンシブ画像
API が遅い並列化 / キャッシュ / streaming
ファイル送信が不安定resumable upload / tus.io
モバイルで遅い転送量を絞る / HTTP/3