Web 前端开发注意事项

前端开发中需要关注的性能、兼容性、安全性等方面

问题

Web 前端开发需要注意哪些事项?

解答

1. 性能优化

<!-- 资源加载优化 -->
<!-- CSS 放头部,避免页面闪烁 -->
<head>
  <link rel="stylesheet" href="style.css">
</head>

<!-- JS 放底部或使用 defer/async -->
<body>
  <!-- 页面内容 -->
  <script src="app.js" defer></script>
</body>
// 图片懒加载
const img = document.querySelector('img');
img.loading = 'lazy';

// 防抖:搜索输入
function debounce(fn, delay) {
  let timer = null;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

// 节流:滚动事件
function throttle(fn, delay) {
  let last = 0;
  return function(...args) {
    const now = Date.now();
    if (now - last >= delay) {
      last = now;
      fn.apply(this, args);
    }
  };
}

2. 兼容性处理

/* CSS 兼容性 */
.box {
  display: -webkit-flex; /* Safari */
  display: flex;
  
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

/* 使用 @supports 检测特性 */
@supports (display: grid) {
  .container {
    display: grid;
  }
}
// JS 特性检测
if ('IntersectionObserver' in window) {
  // 使用 IntersectionObserver
} else {
  // 降级方案
}

// 事件兼容
element.addEventListener('click', handler);
// 老 IE: element.attachEvent('onclick', handler);

3. 安全防护

// XSS 防护:转义用户输入
function escapeHtml(str) {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#x27;'
  };
  return str.replace(/[&<>"']/g, char => map[char]);
}

// 使用 textContent 而非 innerHTML
element.textContent = userInput; // 安全
// element.innerHTML = userInput; // 危险

// CSRF 防护:请求携带 token
fetch('/api/data', {
  method: 'POST',
  headers: {
    'X-CSRF-Token': csrfToken
  }
});

4. 语义化与可访问性

<!-- 语义化标签 -->
<header>
  <nav>
    <a href="/">首页</a>
  </nav>
</header>

<main>
  <article>
    <h1>文章标题</h1>
    <p>内容...</p>
  </article>
</main>

<footer>版权信息</footer>

<!-- 可访问性 -->
<button aria-label="关闭弹窗">×</button>
<img src="photo.jpg" alt="产品图片">
<input type="text" id="name" aria-required="true">
<label for="name">姓名</label>

5. 代码规范

// 使用 const/let,避免 var
const API_URL = 'https://api.example.com';
let count = 0;

// 使用模板字符串
const message = `用户 ${name} 登录成功`;

// 使用可选链和空值合并
const city = user?.address?.city ?? '未知';

// 异步使用 async/await
async function fetchData() {
  try {
    const res = await fetch(API_URL);
    return await res.json();
  } catch (error) {
    console.error('请求失败:', error);
  }
}

6. SEO 优化

<head>
  <!-- 基础 meta -->
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="页面描述,控制在 150 字以内">
  <meta name="keywords" content="关键词1,关键词2">
  
  <!-- Open Graph -->
  <meta property="og:title" content="页面标题">
  <meta property="og:description" content="页面描述">
  
  <title>页面标题 - 网站名</title>
</head>

关键点

  • 性能:资源压缩合并、懒加载、防抖节流、减少重排重绘
  • 兼容性:CSS 前缀、特性检测、polyfill 降级
  • 安全:XSS 转义输入、CSRF token、HTTPS、CSP
  • 语义化:正确使用 HTML5 标签、添加 ARIA 属性
  • 规范:ESLint + Prettier、组件化开发、Git 提交规范