best-practices について
Lighthouse のベストプラクティス監査を基にした Web 開発向けリファレンススキルです。セキュリティ、ブラウザー互換性、パフォーマンス、コード品質を確認するための指針とチェックリストを提供します。
主な機能
- 01セキュリティヘッダーと入力保護
- 02ブラウザー互換性の指針
- 03非推奨 API の代替策
- 04エラー処理とソースマップ
- 05パフォーマンスとメモリー管理
- 06監査チェックリストとツール
活用シーン
- 01Web アプリのセキュリティ確認
- 02ブラウザー互換性の点検
- 03本番環境のエラー削減
- 04パフォーマンスとコード品質の監査
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ tech-leads-club/ agent-skills --skill best-practicesインストール後、Claude Code で/best-practicesを入力して読み込まれたか確認します。
詳細
ベストプラクティス
Lighthouse のベストプラクティス監査に基づく、最新のウェブ開発標準です。セキュリティ、ブラウザー互換性、コード品質に関するパターンを扱います。
セキュリティ
HTTPS を全面的に使用する
HTTPS を強制する:
<img src="http://example.com/image.jpg" />
<script src="http://cdn.example.com/script.js"></script>
<img src="https://example.com/image.jpg" />
<script src="https://cdn.example.com/script.js"></script>
<img src="//example.com/image.jpg" />
HSTS ヘッダー:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
コンテンツセキュリティポリシー(CSP)
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self';
script-src 'self' https://trusted-cdn.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;"
/>
CSP ヘッダー(推奨):
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-abc123' https://trusted.com;
style-src 'self' 'nonce-abc123';
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
frame-ancestors 'self';
base-uri 'self';
form-action 'self';
インラインスクリプトに nonce を使用する:
<script nonce="abc123">
// This inline script is allowed
</script>
セキュリティヘッダー
# Prevent clickjacking
X-Frame-Options: DENY
# Prevent MIME type sniffing
X-Content-Type-Options: nosniff
# Enable XSS filter (legacy browsers)
X-XSS-Protection: 1; mode=block
# Control referrer information
Referrer-Policy: strict-origin-when-cross-origin
# Permissions policy (formerly Feature-Policy)
Permissions-Policy: geolocation=(), microphone=(), camera=()
脆弱なライブラリを使用しない
# Check for vulnerabilities
npm audit
yarn audit
# Auto-fix when possible
npm audit fix
# Check specific package
npm ls lodash
依存関係を最新の状態に保つ:
// package.json
{
"scripts": {
"audit": "npm audit --audit-level=moderate",
"update": "npm update && npm audit fix"
}
}
避けるべき既知の脆弱なパターン:
// ❌ Prototype pollution vulnerable patterns
Object.assign(target, userInput)
_.merge(target, userInput)
// ✅ Safer alternatives
const safeData = JSON.parse(JSON.stringify(userInput))
入力のサニタイズ
// ❌ XSS vulnerable
element.innerHTML = userInput
document.write(userInput)
// ✅ Safe text content
element.textContent = userInput
// ✅ If HTML needed, sanitize
import DOMPurify from 'dompurify'
element.innerHTML = DOMPurify.sanitize(userInput)
Cookie の保護
// ❌ Insecure cookie
document.cookie = "session=abc123";
// ✅ Secure cookie (server-side)
Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=Strict; Path=/
ブラウザー互換性
Doctype 宣言
<html lang="en">
<head>
<title>Page</title>
</head>
<body></body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page</title>
</head>
<body></body>
</html>
文字エンコーディング
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page</title>
<meta charset="UTF-8" />
</head>
<body></body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Page</title>
</head>
<body></body>
</html>
ビューポートの meta タグ
<head>
<title>Page</title>
</head>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Page</title>
</head>
機能検出
// ❌ Browser detection (brittle)
if (navigator.userAgent.includes('Chrome')) {
// Chrome-specific code
}
// ✅ Feature detection
if ('IntersectionObserver' in window) {
// Use IntersectionObserver
} else {
// Fallback
}
// ✅ Using @supports in CSS
@supports (display: grid) {
.container {
display: grid;
}
}
@supports not (display: grid) {
.container {
display: flex;
}
}
ポリフィル(必要な場合)
<script>
if (!('fetch' in window)) {
document.write('<script src="/polyfills/fetch.js"><\/script>')
}
</script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=fetch,IntersectionObserver"></script>
非推奨 API
これらを避ける
// ❌ document.write (blocks parsing)
document.write('<script src="..."></script>');
// ✅ Dynamic script loading
const script = document.createElement('script');
script.src = '...';
document.head.appendChild(script);
// ❌ Synchronous XHR (blocks main thread)
const xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // false = synchronous
// ✅ Async fetch
const response = await fetch(url);
// ❌ Application Cache (deprecated)
<html manifest="cache.manifest">
// ✅ Service Workers
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
イベントリスナーの passive オプション
// ❌ Non-passive touch/wheel (may block scrolling)
element.addEventListener('touchstart', handler)
element.addEventListener('wheel', handler)
// ✅ Passive listeners (allows smooth scrolling)
element.addEventListener('touchstart', handler, { passive: true })
element.addEventListener('wheel', handler, { passive: true })
// ✅ If you need preventDefault, be explicit
element.addEventListener('touchstart', handler, { passive: false })
コンソールとエラー
コンソールエラーをなくす
// ❌ Errors in production
console.log('Debug info') // Remove in production
throw new Error('Unhandled') // Catch all errors
// ✅ Proper error handling
try {
riskyOperation()
} catch (error) {
// Log to error tracking service
errorTracker.captureException(error)
// Show user-friendly message
showErrorMessage('Something went wrong. Please try again.')
}
エラーバウンダリー(React)
class ErrorBoundary extends React.Component {
state = { hasError: false }
static getDerivedStateFromError(error) {
return { hasError: true }
}
componentDidCatch(error, info) {
errorTracker.captureException(error, { extra: info })
}
render() {
if (this.state.hasError) {
return <FallbackUI />
}
return this.props.children
}
}
// Usage
;<ErrorBoundary>
<App />
</ErrorBoundary>
グローバルエラーハンドラー
// Catch unhandled errors
window.addEventListener('error', (event) => {
errorTracker.captureException(event.error)
})
// Catch unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
errorTracker.captureException(event.reason)
})
ソースマップ
本番環境の設定
// ❌ Source maps exposed in production
// webpack.config.js
module.exports = {
devtool: 'source-map', // Exposes source code
}
// ✅ Hidden source maps (uploaded to error tracker)
module.exports = {
devtool: 'hidden-source-map',
}
// ✅ Or no source maps in production
module.exports = {
devtool: process.env.NODE_ENV === 'production' ? false : 'source-map',
}
パフォーマンスのベストプラクティス
ブロックするパターンを避ける
// ❌ Blocking script
<script src="heavy-library.js"></script>
// ✅ Deferred script
<script defer src="heavy-library.js"></script>
// ❌ Blocking CSS import
@import url('other-styles.css');
// ✅ Link tags (parallel loading)
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="other-styles.css">
効率的なイベントハンドラー
// ❌ Handler on every element
items.forEach((item) => {
item.addEventListener('click', handleClick)
})
// ✅ Event delegation
container.addEventListener('click', (e) => {
if (e.target.matches('.item')) {
handleClick(e)
}
})
メモリ管理
// ❌ Memory leak (never removed)
const handler = () => {
/* ... */
}
window.addEventListener('resize', handler)
// ✅ Cleanup when done
const handler = () => {
/* ... */
}
window.addEventListener('resize', handler)
// Later, when component unmounts:
window.removeEventListener('resize', handler)
// ✅ Using AbortController
const controller = new AbortController()
window.addEventListener('resize', handler, { signal: controller.signal })
// Cleanup:
controller.abort()
コード品質
有効な HTML
<div id="header">
<div id="header">
</div>
<ul>
<div>Item</div>
</ul>
<a href="/"><button>Click</button></a>
</div>
<header id="site-header"></header>
<ul>
<li>Item</li>
</ul>
<a href="/" class="button">Click</a>
セマンティック HTML
<div class="header">
<div class="nav">
<div class="nav-item">Home</div>
</div>
</div>
<div class="main">
<div class="article">
<div class="title">Headline</div>
</div>
</div>
<header>
<nav>
<a href="/">Home</a>
</nav>
</header>
<main>
<article>
<h1>Headline</h1>
</article>
</main>
画像のアスペクト比
<img src="photo.jpg" width="300" height="100" />
<img src="photo.jpg" width="300" height="225" />
<img src="photo.jpg" style="width: 300px; height: 200px; object-fit: cover;" />
権限とプライバシー
適切に権限をリクエストする
// ❌ Request on page load (bad UX, often denied)
navigator.geolocation.getCurrentPosition(success, error)
// ✅ Request in context, after user action
findNearbyButton.addEventListener('click', async () => {
// Explain why you need it
if (await showPermissionExplanation()) {
navigator.geolocation.getCurrentPosition(success, error)
}
})
Permissions Policy
<meta http-equiv="Permissions-Policy" content="geolocation=(), camera=(), microphone=()" />
<meta http-equiv="Permissions-Policy" content="geolocation=(self 'https://maps.example.com')" />
監査チェックリスト
セキュリティ(重要)
- HTTPS が有効で、混在コンテンツがない
- 脆弱な依存関係がない(
npm audit) - CSP ヘッダーが設定されている
- セキュリティヘッダーが設定されている
- ソースマップが公開されていない
互換性
- 有効な HTML5 doctype が指定されている
- head の先頭で文字セットが宣言されている
- ビューポートの meta タグが設定されている
- 非推奨 API が使用されていない
- スクロール/タッチに passive イベントリスナーを使用している
コード品質
- コンソールエラーがない
- 有効な HTML(ID の重複がない)
- セマンティック HTML 要素を使用している
- 適切なエラー処理を行っている
- コンポーネント内のメモリを解放している
UX
- 邪魔なインタースティシャルがない
- 適切な状況で権限をリクエストしている
- エラーメッセージが明確である
- 画像のアスペクト比が適切である
ツール
| ツール | 目的 |
|---|---|
npm audit | 依存関係の脆弱性 |
| SecurityHeaders.com | ヘッダーの分析 |
| W3C Validator | HTML の検証 |
| Lighthouse | ベストプラクティスの監査 |
| Observatory | セキュリティスキャン |
参考資料
コメント
Markdown 対応