best-practices by addyosmani/web-quality-skills
npx skills add https://github.com/addyosmani/web-quality-skills --skill best-practices基于 Lighthouse 最佳实践审计的现代 Web 开发标准。涵盖安全性、浏览器兼容性和代码质量模式。
强制使用 HTTPS:
<!-- ❌ 混合内容 -->
<img src="http://example.com/image.jpg">
<script src="http://cdn.example.com/script.js"></script>
<!-- ✅ 仅使用 HTTPS -->
<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
<!-- 通过 meta 标签设置基础 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;">
<!-- 更好:使用 HTTP 头部 -->
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
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">
// 此内联脚本被允许
</script>
# 防止点击劫持
X-Frame-Options: DENY
# 防止 MIME 类型嗅探
X-Content-Type-Options: nosniff
# 启用 XSS 过滤器(旧版浏览器)
X-XSS-Protection: 1; mode=block
# 控制 Referrer 信息
Referrer-Policy: strict-origin-when-cross-origin
# 权限策略(原 Feature-Policy)
Permissions-Policy: geolocation=(), microphone=(), camera=()
# 检查漏洞
npm audit
yarn audit
# 自动修复(如果可能)
npm audit fix
# 检查特定包
npm ls lodash
保持依赖项更新:
// package.json
{
"scripts": {
"audit": "npm audit --audit-level=moderate",
"update": "npm update && npm audit fix"
}
}
应避免的已知易受攻击模式:
// ❌ 易受原型污染的模式
Object.assign(target, userInput);
_.merge(target, userInput);
// ✅ 更安全的替代方案
const safeData = JSON.parse(JSON.stringify(userInput));
// ❌ 易受 XSS 攻击
element.innerHTML = userInput;
document.write(userInput);
// ✅ 安全的文本内容
element.textContent = userInput;
// ✅ 如果需要 HTML,进行净化
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);
// ❌ 不安全的 Cookie
document.cookie = "session=abc123";
// ✅ 安全的 Cookie(服务器端)
Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=Strict; Path=/
<!-- ❌ 缺少或无效的 doctype -->
<HTML>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<!-- ✅ HTML5 doctype -->
<!DOCTYPE html>
<html lang="en">
<!-- ❌ 缺少或 charset 声明过晚 -->
<html>
<head>
<title>Page</title>
<meta charset="UTF-8">
</head>
<!-- ✅ Charset 作为 head 中的第一个元素 -->
<html>
<head>
<meta charset="UTF-8">
<title>Page</title>
</head>
<!-- ❌ 缺少 viewport -->
<head>
<title>Page</title>
</head>
<!-- ✅ 响应式视口 -->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page</title>
</head>
// ❌ 浏览器检测(脆弱)
if (navigator.userAgent.includes('Chrome')) {
// Chrome 特定代码
}
// ✅ 特性检测
if ('IntersectionObserver' in window) {
// 使用 IntersectionObserver
} else {
// 回退方案
}
// ✅ 在 CSS 中使用 @supports
@supports (display: grid) {
.container {
display: grid;
}
}
@supports not (display: grid) {
.container {
display: flex;
}
}
<!-- 有条件地加载 polyfills -->
<script>
if (!('fetch' in window)) {
document.write('<script src="/polyfills/fetch.js"><\/script>');
}
</script>
<!-- 或使用 polyfill.io -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=fetch,IntersectionObserver"></script>
// ❌ document.write(阻塞解析)
document.write('<script src="..."></script>');
// ✅ 动态脚本加载
const script = document.createElement('script');
script.src = '...';
document.head.appendChild(script);
// ❌ 同步 XHR(阻塞主线程)
const xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // false = 同步
// ✅ 异步 fetch
const response = await fetch(url);
// ❌ Application Cache(已弃用)
<html manifest="cache.manifest">
// ✅ Service Workers
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
// ❌ 非被动 touch/wheel 监听器(可能阻塞滚动)
element.addEventListener('touchstart', handler);
element.addEventListener('wheel', handler);
// ✅ 被动监听器(允许平滑滚动)
element.addEventListener('touchstart', handler, { passive: true });
element.addEventListener('wheel', handler, { passive: true });
// ✅ 如果需要 preventDefault,请明确声明
element.addEventListener('touchstart', handler, { passive: false });
// ❌ 生产环境中的错误
console.log('调试信息'); // 在生产环境中移除
throw new Error('未处理'); // 捕获所有错误
// ✅ 正确的错误处理
try {
riskyOperation();
} catch (error) {
// 记录到错误追踪服务
errorTracker.captureException(error);
// 显示用户友好的消息
showErrorMessage('出错了。请重试。');
}
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;
}
}
// 用法
<ErrorBoundary>
<App />
</ErrorBoundary>
// 捕获未处理的错误
window.addEventListener('error', (event) => {
errorTracker.captureException(event.error);
});
// 捕获未处理的 Promise 拒绝
window.addEventListener('unhandledrejection', (event) => {
errorTracker.captureException(event.reason);
});
// ❌ 生产环境中暴露 source maps
// webpack.config.js
module.exports = {
devtool: 'source-map', // 暴露源代码
};
// ✅ 隐藏的 source maps(上传到错误追踪器)
module.exports = {
devtool: 'hidden-source-map',
};
// ✅ 或者生产环境中不使用 source maps
module.exports = {
devtool: process.env.NODE_ENV === 'production' ? false : 'source-map',
};
// ❌ 阻塞脚本
<script src="heavy-library.js"></script>
// ✅ 延迟脚本
<script defer src="heavy-library.js"></script>
// ❌ 阻塞的 CSS 导入
@import url('other-styles.css');
// ✅ Link 标签(并行加载)
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="other-styles.css">
// ❌ 为每个元素添加处理器
items.forEach(item => {
item.addEventListener('click', handleClick);
});
// ✅ 事件委托
container.addEventListener('click', (e) => {
if (e.target.matches('.item')) {
handleClick(e);
}
});
// ❌ 内存泄漏(从未移除)
const handler = () => { /* ... */ };
window.addEventListener('resize', handler);
// ✅ 完成后清理
const handler = () => { /* ... */ };
window.addEventListener('resize', handler);
// 稍后,当组件卸载时:
window.removeEventListener('resize', handler);
// ✅ 使用 AbortController
const controller = new AbortController();
window.addEventListener('resize', handler, { signal: controller.signal });
// 清理:
controller.abort();
<!-- ❌ 无效的 HTML -->
<div id="header">
<div id="header"> <!-- 重复的 ID -->
<ul>
<div>Item</div> <!-- 无效的子元素 -->
</ul>
<a href="/"><button>Click</button></a> <!-- 无效的嵌套 -->
<!-- ✅ 有效的 HTML -->
<header id="site-header">
</header>
<ul>
<li>Item</li>
</ul>
<a href="/" class="button">Click</a>
<!-- ❌ 非语义化 -->
<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>
<!-- ✅ 语义化 HTML5 -->
<header>
<nav>
<a href="/">Home</a>
</nav>
</header>
<main>
<article>
<h1>Headline</h1>
</article>
</main>
<!-- ❌ 扭曲的图像 -->
<img src="photo.jpg" width="300" height="100">
<!-- 如果实际宽高比是 4:3,这会挤压图像 -->
<!-- ✅ 保持宽高比 -->
<img src="photo.jpg" width="300" height="225">
<!-- 实际的 4:3 尺寸 -->
<!-- ✅ 使用 CSS object-fit 以获得灵活性 -->
<img src="photo.jpg" style="width: 300px; height: 200px; object-fit: cover;">
// ❌ 在页面加载时请求(用户体验差,常被拒绝)
navigator.geolocation.getCurrentPosition(success, error);
// ✅ 在上下文中,用户操作后请求
findNearbyButton.addEventListener('click', async () => {
// 解释为什么需要它
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')">
npm audit)| 工具 | 用途 |
|---|---|
npm audit | 依赖项漏洞 |
| SecurityHeaders.com | 头部分析 |
| W3C Validator | HTML 验证 |
| Lighthouse | 最佳实践审计 |
| Observatory | 安全扫描 |
每周安装量
2.7K
代码仓库
GitHub 星标数
1.4K
首次出现
2026年1月20日
安全审计
安装于
opencode2.4K
gemini-cli2.4K
codex2.4K
github-copilot2.3K
cursor2.2K
kimi-cli2.2K
Modern web development standards based on Lighthouse best practices audits. Covers security, browser compatibility, and code quality patterns.
Enforce HTTPS:
<!-- ❌ Mixed content -->
<img src="http://example.com/image.jpg">
<script src="http://cdn.example.com/script.js"></script>
<!-- ✅ HTTPS only -->
<img src="https://example.com/image.jpg">
<script src="https://cdn.example.com/script.js"></script>
<!-- ✅ Protocol-relative (will use page's protocol) -->
<img src="//example.com/image.jpg">
HSTS Header:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
<!-- Basic CSP via meta tag -->
<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;">
<!-- Better: HTTP header -->
CSP Header (recommended):
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';
Using nonces for inline scripts:
<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
Keep dependencies updated:
// package.json
{
"scripts": {
"audit": "npm audit --audit-level=moderate",
"update": "npm update && npm audit fix"
}
}
Known vulnerable patterns to avoid:
// ❌ 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);
// ❌ Insecure cookie
document.cookie = "session=abc123";
// ✅ Secure cookie (server-side)
Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=Strict; Path=/
<!-- ❌ Missing or invalid doctype -->
<HTML>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<!-- ✅ HTML5 doctype -->
<!DOCTYPE html>
<html lang="en">
<!-- ❌ Missing or late charset -->
<html>
<head>
<title>Page</title>
<meta charset="UTF-8">
</head>
<!-- ✅ Charset as first element in head -->
<html>
<head>
<meta charset="UTF-8">
<title>Page</title>
</head>
<!-- ❌ Missing viewport -->
<head>
<title>Page</title>
</head>
<!-- ✅ Responsive viewport -->
<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;
}
}
<!-- Load polyfills conditionally -->
<script>
if (!('fetch' in window)) {
document.write('<script src="/polyfills/fetch.js"><\/script>');
}
</script>
<!-- Or use polyfill.io -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=fetch,IntersectionObserver"></script>
// ❌ 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');
}
// ❌ 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.');
}
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();
<!-- ❌ Invalid HTML -->
<div id="header">
<div id="header"> <!-- Duplicate ID -->
<ul>
<div>Item</div> <!-- Invalid child -->
</ul>
<a href="/"><button>Click</button></a> <!-- Invalid nesting -->
<!-- ✅ Valid HTML -->
<header id="site-header">
</header>
<ul>
<li>Item</li>
</ul>
<a href="/" class="button">Click</a>
<!-- ❌ Non-semantic -->
<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>
<!-- ✅ Semantic HTML5 -->
<header>
<nav>
<a href="/">Home</a>
</nav>
</header>
<main>
<article>
<h1>Headline</h1>
</article>
</main>
<!-- ❌ Distorted images -->
<img src="photo.jpg" width="300" height="100">
<!-- If actual ratio is 4:3, this squishes the image -->
<!-- ✅ Preserve aspect ratio -->
<img src="photo.jpg" width="300" height="225">
<!-- Actual 4:3 dimensions -->
<!-- ✅ CSS object-fit for flexibility -->
<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);
}
});
<!-- Restrict powerful features -->
<meta http-equiv="Permissions-Policy"
content="geolocation=(), camera=(), microphone=()">
<!-- Or allow for specific origins -->
<meta http-equiv="Permissions-Policy"
content="geolocation=(self 'https://maps.example.com')">
npm audit)| Tool | Purpose |
|---|---|
npm audit | Dependency vulnerabilities |
| SecurityHeaders.com | Header analysis |
| W3C Validator | HTML validation |
| Lighthouse | Best practices audit |
| Observatory | Security scan |
Weekly Installs
2.7K
Repository
GitHub Stars
1.4K
First Seen
Jan 20, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode2.4K
gemini-cli2.4K
codex2.4K
github-copilot2.3K
cursor2.2K
kimi-cli2.2K
97,600 周安装