SEO 优化
前端 SEO 优化的常用方法和实践
问题
前端开发中如何进行 SEO 优化?
解答
1. HTML 语义化
<!-- 不好的写法 -->
<div class="header">
<div class="nav">...</div>
</div>
<div class="content">
<div class="article">...</div>
</div>
<!-- 好的写法 -->
<header>
<nav>...</nav>
</header>
<main>
<article>
<h1>文章标题</h1>
<section>...</section>
</article>
</main>
<footer>...</footer>
2. Meta 标签优化
<head>
<!-- 页面标题,建议 50-60 字符 -->
<title>产品名称 - 简短描述</title>
<!-- 页面描述,建议 150-160 字符 -->
<meta name="description" content="页面的简短描述,会显示在搜索结果中">
<!-- 关键词(现代搜索引擎权重较低) -->
<meta name="keywords" content="关键词1,关键词2">
<!-- 规范链接,避免重复内容 -->
<link rel="canonical" href="https://example.com/page">
<!-- Open Graph 标签,用于社交分享 -->
<meta property="og:title" content="页面标题">
<meta property="og:description" content="页面描述">
<meta property="og:image" content="https://example.com/image.jpg">
<meta property="og:url" content="https://example.com/page">
<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image">
</head>
3. 结构化数据 (JSON-LD)
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "文章标题",
"author": {
"@type": "Person",
"name": "作者名"
},
"datePublished": "2024-01-01",
"image": "https://example.com/image.jpg"
}
</script>
4. 图片优化
<!-- 添加 alt 属性 -->
<img
src="product.jpg"
alt="红色运动鞋侧面图"
width="800"
height="600"
loading="lazy"
>
<!-- 响应式图片 -->
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="描述">
</picture>
5. URL 结构
# 好的 URL
https://example.com/blog/seo-optimization-guide
# 不好的 URL
https://example.com/page?id=123&cat=5
6. 服务端渲染 (SSR) / 静态生成 (SSG)
// Next.js SSG 示例
export async function getStaticProps() {
const data = await fetchData()
return {
props: { data },
revalidate: 3600 // ISR: 每小时重新生成
}
}
// Next.js SSR 示例
export async function getServerSideProps() {
const data = await fetchData()
return { props: { data } }
}
7. Sitemap 和 Robots.txt
<!-- sitemap.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://example.com/</loc>
<lastmod>2024-01-01</lastmod>
<priority>1.0</priority>
</url>
<url>
<loc>https://example.com/about</loc>
<lastmod>2024-01-01</lastmod>
<priority>0.8</priority>
</url>
</urlset>
# robots.txt
User-agent: *
Allow: /
Disallow: /admin/
Disallow: /api/
Sitemap: https://example.com/sitemap.xml
8. 性能优化
// 预加载关键资源
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="main.js" as="script">
// DNS 预解析
<link rel="dns-prefetch" href="//api.example.com">
// 预连接
<link rel="preconnect" href="https://fonts.googleapis.com">
关键点
- 语义化 HTML:使用正确的标签(header、nav、main、article、section)帮助搜索引擎理解页面结构
- Meta 标签:title 控制在 60 字符内,description 控制在 160 字符内
- SSR/SSG:SPA 应用使用服务端渲染或静态生成,确保爬虫能获取完整内容
- 结构化数据:使用 JSON-LD 提供机器可读的页面信息,可获得富媒体搜索结果
- 性能优化:Core Web Vitals(LCP、FID、CLS)是 Google 排名因素之一
- 移动端适配:Google 采用移动优先索引,确保移动端体验良好
目录