关于 best-practices
基于 Lighthouse 最佳实践审计的 Web 开发参考 Skill,帮助开发者检查安全、浏览器兼容性、性能、代码质量和用户体验,并提供实践建议与清单。
主要功能
- 01安全标头与输入处理
- 02浏览器兼容性建议
- 03性能与内存管理实践
- 04错误处理和代码质量检查
- 05审计清单与工具参考
适用场景
- 01检查网站安全配置
- 02排查浏览器兼容性和弃用 API
- 03审查性能与生产环境错误
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ davila7/ claude-code-templates --skill best-practices安装后在 Claude Code 中输入/best-practices确认已加载。
详细介绍
最佳实践
基于 Lighthouse 最佳实践审计的现代 Web 开发标准。涵盖安全性、浏览器兼容性和代码质量模式。
安全性
全面启用 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>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<!DOCTYPE html>
<html lang="en">
字符编码
<html>
<head>
<title>Page</title>
<meta charset="UTF-8">
</head>
<html>
<head>
<meta charset="UTF-8">
<title>Page</title>
</head>
Viewport 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;
}
}
Polyfill(按需使用)
<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 map
生产环境配置
// ❌ 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">
<ul>
<div>Item</div>
</ul>
<a href="/"><button>Click</button></a>
<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);
}
});
权限策略
<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 响应头
- 已设置安全响应头
- 未暴露 source map
兼容性
- 有效的 HTML5 doctype
- 字符集在 head 中最先声明
- 存在 viewport meta 标签
- 未使用已弃用的 API
- 为滚动/触摸事件使用 passive 事件监听器
代码质量
- 无控制台错误
- 有效的 HTML(无重复 ID)
- 使用了语义化 HTML 元素
- 正确的错误处理
- 组件中进行了内存清理
用户体验
- 无侵入式插页
- 在恰当的上下文中请求权限
- 清晰的错误消息
- 合适的图片宽高比
工具
| 工具 | 用途 |
|---|---|
npm audit | 依赖项漏洞 |
| SecurityHeaders.com | 响应头分析 |
| W3C Validator | HTML 验证 |
| Lighthouse | 最佳实践审计 |
| Observatory | 安全扫描 |
参考资料
评论
支持 Markdown