页面重构方法
前端页面重构的操作步骤和常用技巧
问题
页面重构怎么操作?
解答
页面重构是在不改变页面外观和功能的前提下,优化代码结构、提升性能和可维护性。
1. HTML 结构优化
<!-- 重构前:div 滥用 -->
<div class="header">
<div class="logo">Logo</div>
<div class="nav">
<div class="nav-item">首页</div>
<div class="nav-item">关于</div>
</div>
</div>
<!-- 重构后:语义化标签 -->
<header>
<h1 class="logo">Logo</h1>
<nav>
<ul>
<li><a href="/">首页</a></li>
<li><a href="/about">关于</a></li>
</ul>
</nav>
</header>
2. CSS 重构
/* 重构前:重复样式 */
.btn-primary {
padding: 10px 20px;
border-radius: 4px;
font-size: 14px;
background: blue;
color: white;
}
.btn-danger {
padding: 10px 20px;
border-radius: 4px;
font-size: 14px;
background: red;
color: white;
}
/* 重构后:提取公共样式 */
.btn {
padding: 10px 20px;
border-radius: 4px;
font-size: 14px;
color: white;
}
.btn-primary { background: blue; }
.btn-danger { background: red; }
3. JavaScript 重构
// 重构前:重复逻辑
function getUserName(user) {
if (user && user.profile && user.profile.name) {
return user.profile.name;
}
return 'Unknown';
}
function getUserAge(user) {
if (user && user.profile && user.profile.age) {
return user.profile.age;
}
return 0;
}
// 重构后:提取通用函数
function getProfileField(user, field, defaultValue) {
return user?.profile?.[field] ?? defaultValue;
}
const userName = getProfileField(user, 'name', 'Unknown');
const userAge = getProfileField(user, 'age', 0);
4. 资源优化
<!-- 图片优化 -->
<img
src="image.webp"
srcset="image-320.webp 320w, image-640.webp 640w"
sizes="(max-width: 320px) 320px, 640px"
loading="lazy"
alt="描述"
>
<!-- CSS/JS 加载优化 -->
<link rel="preload" href="critical.css" as="style">
<script src="app.js" defer></script>
5. 组件化重构
// 重构前:页面级代码
document.querySelector('.tab-1').onclick = () => { /* ... */ };
document.querySelector('.tab-2').onclick = () => { /* ... */ };
// 重构后:可复用组件
class Tabs {
constructor(container) {
this.container = container;
this.tabs = container.querySelectorAll('.tab');
this.panels = container.querySelectorAll('.panel');
this.bindEvents();
}
bindEvents() {
this.tabs.forEach((tab, index) => {
tab.addEventListener('click', () => this.switchTo(index));
});
}
switchTo(index) {
this.tabs.forEach((t, i) => t.classList.toggle('active', i === index));
this.panels.forEach((p, i) => p.classList.toggle('active', i === index));
}
}
// 可在多处复用
new Tabs(document.querySelector('#tabs-1'));
new Tabs(document.querySelector('#tabs-2'));
关键点
- 语义化 HTML:用正确的标签表达内容含义,提升可访问性和 SEO
- CSS 复用:提取公共样式,使用 BEM 或 CSS Modules 管理命名
- JS 模块化:拆分功能,消除重复代码,提高可测试性
- 性能优化:压缩资源、懒加载、减少 HTTP 请求
- 渐进式重构:小步迭代,每次改动后验证功能正常
目录