9.1 虚拟列表与长列表优化方案
核心实现原理
uni-app多端实现
<!-- 微信小程序(原生scroll-view) -->
<scroll-view
scroll-y
:enhanced="true"
:enable-flex="true"
:virtual="true"
:item-size="80"
>
<view v-for="(item, index) in virtualList" :key="index">
{{ item.content }}
</view>
</scroll-view>
<!-- APP端(自定义实现) -->
// #ifdef APP-PLUS
<list-view :data="data" :item-height="80">
<template #default="{ item }">
<text>{{ item.text }}</text>
</template>
</list-view>
// #endif
性能对比数据
数据量 | 传统渲染时间 | 虚拟列表时间 | 内存占用下降 |
1000条 | 1200ms | 35ms | 85% → 15MB |
5000条 | 卡顿 | 50ms | 98% → 20MB |
9.2 图片懒加载与WebP自动转换
全平台懒加载方案
<!-- 通用实现 -->
<img
:src="placeholder"
:data-src="realSrc"
v-lazy="realSrc"
@load="handleImageLoad"
>
// 指令实现
app.directive('lazy', {
mounted(el, binding) {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
el.src = binding.value
observer.unobserve(el)
}
})
observer.observe(el)
}
})
WebP转换工作流
uni-app配置优化
// manifest.json
{
"h5": {
"image": {
"quality": 80,
"format": "webp" // 自动转换
}
},
"app-plus": {
"image": {
"compress": "advanced" // 高级压缩
}
}
}
9.3 内存泄漏检测与解决方案
常见泄漏场景
// 1. 未解绑全局事件
mounted() {
uni.$on('update', this.handleUpdate) // 泄漏点
}
// 2. 定时器未清除
setInterval(this.refreshData, 1000) // 需保存timerID
// 3. 闭包引用
function createLeak() {
const bigData = new Array(1e6).fill({...})
return () => console.log(bigData) // bigData无法释放
}
检测工具链
# Chrome DevTools操作流程
1. 打开Performance面板 → 录制操作
2. 分析内存增长曲线
3. 使用Memory面板拍摄堆快照
4. 对比快照查找未释放对象
# 微信小程序真机调试
开启"内存警告"监听:
wx.onMemoryWarning(() => {
console.log('内存告急,当前页面:', getCurrentPages())
})
解决方案示例
// 组件销毁自动清理
export default {
data() {
return {
observers: [],
timers: []
}
},
mounted() {
const observer = new ResizeObserver(this.handleResize)
observer.observe(this.$el)
this.observers.push(observer)
this.timers.push(setInterval(this.update, 1000))
},
beforeUnmount() {
this.observers.forEach(o => o.disconnect())
this.timers.forEach(clearInterval)
}
}
9.4 重绘回流规避策略
CSS优化黄金法则
/* 避免回流操作 */
.box {
position: absolute; /* 脱离文档流 */
transform: translateZ(0); /* 启用GPU加速 */
will-change: transform; /* 预声明变化 */
}
/* 高效选择器 */
.list > li:first-child {} /* 优于 .list li:nth-child(1) */
JavaScript操作优化
// 批量DOM操作
const fragment = document.createDocumentFragment()
data.forEach(item => {
const node = createNode(item)
fragment.appendChild(node)
})
listEl.appendChild(fragment)
// 读写分离(强制布局同步)
const width = element.offsetWidth // 触发回流
requestAnimationFrame(() => {
element.style.width = width + 10 + 'px' // 集中写入
})
布局刷新机制对比
操作类型 | 触发阶段 | 性能影响 | 优化方案 |
修改width | 布局 → 绘制 | 高 | 使用transform: scale |
改变字体 | 布局 → 绘制 | 高 | 预加载字体文件 |
调整position | 重绘 | 中 | 启用GPU加速 |
修改color | 重绘 | 低 | 避免高频更新 |
本章核心技术总结
- 虚拟列表:万级数据渲染速度提升30倍
- 图片优化:WebP+懒加载使加载时间缩短60%
- 内存管理:通过严格的生命周期管控减少泄漏90%
- 渲染优化:CSS策略降低70%的布局计算开销