性能优化技巧
全面的移动端性能优化策略,帮助你构建高性能的Vant应用。
📦 包体积优化
按需引入组件
自动按需引入(推荐)
bash
# 安装依赖
npm install unplugin-vue-components -D
javascript
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
vue(),
Components({
resolvers: [VantResolver()]
})
]
})
vue
<template>
<!-- 无需手动导入,自动按需加载 -->
<van-button type="primary">按钮</van-button>
<van-cell title="单元格" />
</template>
手动按需引入
javascript
// main.js
import { createApp } from 'vue'
import { Button, Cell, Toast } from 'vant'
import 'vant/es/button/style'
import 'vant/es/cell/style'
import 'vant/es/toast/style'
const app = createApp()
app.use(Button)
app.use(Cell)
app.use(Toast)
代码分割
路由级代码分割
javascript
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue')
},
{
path: '/products',
name: 'Products',
component: () => import('../views/Products.vue')
},
{
path: '/profile',
name: 'Profile',
// 懒加载 + 预加载
component: () => import(/* webpackChunkName: "profile" */ '../views/Profile.vue')
}
]
export default createRouter({
history: createWebHistory(),
routes
})
组件级代码分割
vue
<script setup>
import { defineAsyncComponent } from 'vue'
// 异步组件
const HeavyComponent = defineAsyncComponent(() =>
import('./components/HeavyComponent.vue')
)
// 带加载状态的异步组件
const AsyncComponent = defineAsyncComponent({
loader: () => import('./components/AsyncComponent.vue'),
loadingComponent: LoadingComponent,
errorComponent: ErrorComponent,
delay: 200,
timeout: 3000
})
</script>
<template>
<div>
<HeavyComponent />
<AsyncComponent />
</div>
</template>
构建优化配置
Vite 配置优化
javascript
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
build: {
// 启用CSS代码分割
cssCodeSplit: true,
// 构建后是否生成source map文件
sourcemap: false,
// chunk大小警告的限制
chunkSizeWarningLimit: 2000,
rollupOptions: {
output: {
// 手动分包
manualChunks: {
'vue-vendor': ['vue', 'vue-router', 'pinia'],
'vant-vendor': ['vant'],
'utils-vendor': ['lodash-es', 'dayjs']
}
}
},
// 压缩配置
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
pure_funcs: ['console.log']
}
}
},
// 开发服务器优化
server: {
warmup: {
clientFiles: ['./src/components/*.vue']
}
}
})
⚡ 运行时性能优化
图片优化策略
懒加载实现
vue
<script setup>
import { ref, onMounted } from 'vue'
import { Lazyload } from 'vant'
// 图片懒加载配置
const lazyloadOptions = {
preLoad: 1.3,
error: '/error.png',
loading: '/loading.gif',
attempt: 1
}
onMounted(() => {
app.use(Lazyload, lazyloadOptions)
})
</script>
<template>
<!-- 图片懒加载 -->
<img v-lazy="imageUrl" alt="懒加载图片" />
<!-- 背景图懒加载 -->
<div v-lazy:background-image="bgImageUrl" class="bg-container"></div>
<!-- Vant 图片组件懒加载 -->
<van-image
lazy-load
:src="imageUrl"
width="100"
height="100"
fit="cover"
/>
</template>
响应式图片
html
<!-- 根据设备像素比加载不同分辨率图片 -->
<img
srcset="image@1x.jpg 1x, image@2x.jpg 2x, image@3x.jpg 3x"
src="image@1x.jpg"
alt="响应式图片"
>
<!-- 使用 picture 元素支持多种格式 -->
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="图片">
</picture>
虚拟滚动
vue
<script setup>
import { ref, computed, onMounted } from 'vue'
import { List } from 'vant'
const list = ref([])
const loading = ref(false)
const finished = ref(false)
// 虚拟滚动配置
const itemHeight = 60
const visibleCount = Math.ceil(window.innerHeight / itemHeight) + 2
const startIndex = ref(0)
const visibleItems = computed(() => {
const start = startIndex.value
const end = start + visibleCount
return list.value.slice(start, end)
})
const onLoad = async () => {
loading.value = true
// 模拟加载数据
const newItems = Array.from({ length: 20 }, (_, i) => ({
id: list.value.length + i,
title: `项目 ${list.value.length + i + 1}`
}))
list.value.push(...newItems)
loading.value = false
if (list.value.length >= 100) {
finished.value = true
}
}
const onScroll = (event) => {
const scrollTop = event.target.scrollTop
startIndex.value = Math.floor(scrollTop / itemHeight)
}
</script>
<template>
<div class="virtual-list" @scroll="onScroll">
<van-list
v-model:loading="loading"
:finished="finished"
finished-text="没有更多了"
@load="onLoad"
>
<van-cell
v-for="item in visibleItems"
:key="item.id"
:title="item.title"
:style="{ height: itemHeight + 'px' }"
/>
</van-list>
</div>
</template>
<style scoped>
.virtual-list {
height: 400px;
overflow-y: auto;
}
</style>
🚀 首屏加载优化
关键资源优化
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- DNS预解析 -->
<link rel="dns-prefetch" href="//cdn.example.com">
<link rel="dns-prefetch" href="//api.example.com">
<!-- 预加载关键资源 -->
<link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="/css/critical.css" as="style">
<!-- 预连接重要的第三方源 -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<!-- 内联关键CSS -->
<style>
/* 首屏关键样式 */
.loading-screen {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #fff;
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
}
.loading-spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #1989fa;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
<title>Vant移动端UI</title>
</head>
<body>
<div id="app">
<!-- 首屏加载动画 -->
<div class="loading-screen">
<div class="loading-spinner"></div>
</div>
</div>
</body>
</html>
骨架屏实现
vue
<script setup>
import { ref, onMounted } from 'vue'
import { Skeleton } from 'vant'
const loading = ref(true)
const data = ref([])
const fetchData = async () => {
// 模拟API请求
return new Promise(resolve => {
setTimeout(() => {
resolve([
{ id: 1, title: '标题1', value: '内容1' },
{ id: 2, title: '标题2', value: '内容2' },
{ id: 3, title: '标题3', value: '内容3' }
])
}, 2000)
})
}
onMounted(async () => {
try {
data.value = await fetchData()
} finally {
loading.value = false
}
})
</script>
<template>
<div class="page-container">
<!-- 骨架屏 -->
<van-skeleton
:loading="loading"
:row="3"
:row-width="['100%', '60%', '80%']"
avatar
title
>
<!-- 实际内容 -->
<div class="content">
<van-cell-group>
<van-cell
v-for="item in data"
:key="item.id"
:title="item.title"
:value="item.value"
/>
</van-cell-group>
</div>
</van-skeleton>
</div>
</template>
<style scoped>
.page-container {
padding: 16px;
}
</style>
📱 移动端性能优化
触摸优化
css
/* 触摸延迟优化 */
.touch-element {
/* 消除300ms点击延迟 */
touch-action: manipulation;
/* 禁用触摸高亮 */
-webkit-tap-highlight-color: transparent;
/* 禁用长按菜单 */
-webkit-touch-callout: none;
/* 禁用文本选择 */
-webkit-user-select: none;
user-select: none;
}
/* 滚动优化 */
.scroll-container {
/* 启用硬件加速滚动 */
-webkit-overflow-scrolling: touch;
overflow-scrolling: touch;
/* 优化滚动性能 */
will-change: scroll-position;
/* 防止滚动穿透 */
overscroll-behavior: contain;
}
/* 长列表优化 */
.list-item {
/* 启用GPU加速 */
transform: translateZ(0);
/* 优化重绘 */
will-change: transform;
}
内存优化
vue
<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
const data = ref([])
const observer = ref(null)
// 清理定时器
const timers = []
const addTimer = (callback, delay) => {
const timer = setTimeout(callback, delay)
timers.push(timer)
return timer
}
// 清理事件监听器
const eventListeners = []
const addEventListener = (element, event, handler) => {
element.addEventListener(event, handler)
eventListeners.push({ element, event, handler })
}
onMounted(() => {
// 使用 Intersection Observer 优化滚动性能
observer.value = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// 元素进入视口时的处理
entry.target.classList.add('visible')
}
})
})
// 观察所有列表项
nextTick(() => {
document.querySelectorAll('.list-item').forEach(item => {
observer.value.observe(item)
})
})
})
onUnmounted(() => {
// 清理定时器
timers.forEach(timer => clearTimeout(timer))
// 清理事件监听器
eventListeners.forEach(({ element, event, handler }) => {
element.removeEventListener(event, handler)
})
// 清理 Intersection Observer
if (observer.value) {
observer.value.disconnect()
}
})
</script>
📊 性能监控
性能指标监控
javascript
// 性能监控工具
class PerformanceMonitor {
constructor() {
this.metrics = {}
this.init()
}
init() {
this.observePageLoad()
this.observeUserInteraction()
this.observeResourceLoad()
}
// 页面加载性能
observePageLoad() {
window.addEventListener('load', () => {
const navigation = performance.getEntriesByType('navigation')[0]
this.metrics.pageLoad = {
dns: navigation.domainLookupEnd - navigation.domainLookupStart,
tcp: navigation.connectEnd - navigation.connectStart,
request: navigation.responseStart - navigation.requestStart,
response: navigation.responseEnd - navigation.responseStart,
dom: navigation.domContentLoadedEventEnd - navigation.responseEnd,
load: navigation.loadEventEnd - navigation.loadEventStart,
total: navigation.loadEventEnd - navigation.navigationStart
}
this.reportMetrics()
})
}
// 用户交互性能
observeUserInteraction() {
// 监控 FID (First Input Delay)
if ('PerformanceObserver' in window) {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.name === 'first-input') {
this.metrics.fid = entry.processingStart - entry.startTime
}
}
}).observe({ type: 'first-input', buffered: true })
// 监控 LCP (Largest Contentful Paint)
new PerformanceObserver((list) => {
const entries = list.getEntries()
const lastEntry = entries[entries.length - 1]
this.metrics.lcp = lastEntry.startTime
}).observe({ type: 'largest-contentful-paint', buffered: true })
}
}
// 资源加载性能
observeResourceLoad() {
if ('PerformanceObserver' in window) {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.initiatorType === 'img') {
this.metrics.imageLoad = entry.duration
}
}
}).observe({ type: 'resource', buffered: true })
}
}
// 上报性能数据
reportMetrics() {
// 发送到分析服务
if (navigator.sendBeacon) {
navigator.sendBeacon('/api/performance', JSON.stringify(this.metrics))
} else {
fetch('/api/performance', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.metrics)
}).catch(err => console.error('Performance report failed:', err))
}
}
}
// 初始化性能监控
if (typeof window !== 'undefined') {
new PerformanceMonitor()
}
Web Vitals 监控
javascript
// 安装 web-vitals
// npm install web-vitals
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals'
// 监控核心 Web 性能指标
function sendToAnalytics(metric) {
// 发送到分析服务
fetch('/api/analytics', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(metric)
})
}
getCLS(sendToAnalytics) // 累积布局偏移
getFID(sendToAnalytics) // 首次输入延迟
getFCP(sendToAnalytics) // 首次内容绘制
getLCP(sendToAnalytics) // 最大内容绘制
getTTFB(sendToAnalytics) // 首字节时间
🛠️ 调试工具
性能分析工具推荐
Chrome DevTools
- Performance 面板:分析运行时性能
- Network 面板:分析资源加载
- Lighthouse:综合性能评估
Bundle Analyzer
bash# 安装 npm install --save-dev webpack-bundle-analyzer # 分析包体积 npm run build -- --analyze
性能监控服务
- Google Analytics
- Sentry Performance
- New Relic Browser
性能优化检查清单
- [ ] 启用按需引入,减少包体积
- [ ] 配置代码分割,优化加载速度
- [ ] 实现图片懒加载和压缩
- [ ] 使用骨架屏提升用户体验
- [ ] 优化关键渲染路径
- [ ] 启用资源压缩和缓存
- [ ] 监控核心性能指标
- [ ] 定期进行性能测试
📚 相关资源
💡 最佳实践总结
- 包体积优化:使用按需引入和代码分割
- 首屏优化:实现骨架屏和关键资源预加载
- 运行时优化:使用虚拟滚动和图片懒加载
- 移动端优化:优化触摸体验和滚动性能
- 性能监控:建立完善的性能监控体系
- 持续优化:定期分析和优化性能瓶颈
通过以上优化策略,可以显著提升 Vant 应用的性能表现,为用户提供更好的使用体验。