Performance Optimization Tips
Comprehensive mobile performance optimization strategies to help you build high-performance Vant applications.
📦 Bundle Size Optimization
On-demand Component Import
Automatic On-demand Import (Recommended)
bash
# Install dependencies
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>
<!-- No manual import needed, automatically loaded on demand -->
<van-button type="primary">Button</van-button>
<van-cell title="Cell" />
</template>
Manual On-demand Import
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)
Code Splitting
Route-level Code Splitting
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',
// Lazy loading + preloading
component: () => import(/* webpackChunkName: "profile" */ '../views/Profile.vue')
}
]
export default createRouter({
history: createWebHistory(),
routes
})
Component-level Code Splitting
vue
<script setup>
import { defineAsyncComponent } from 'vue'
// Async component
const HeavyComponent = defineAsyncComponent(() =>
import('./components/HeavyComponent.vue')
)
// Async component with loading state
const AsyncComponent = defineAsyncComponent({
loader: () => import('./components/AsyncComponent.vue'),
loadingComponent: LoadingComponent,
errorComponent: ErrorComponent,
delay: 200,
timeout: 3000
})
</script>
<template>
<div>
<HeavyComponent />
<AsyncComponent />
</div>
</template>
Build Optimization Configuration
Vite Configuration Optimization
javascript
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
build: {
// Enable CSS code splitting
cssCodeSplit: true,
// Generate source map files after build
sourcemap: false,
// Chunk size warning limit
chunkSizeWarningLimit: 2000,
rollupOptions: {
output: {
// Manual chunking
manualChunks: {
'vue-vendor': ['vue', 'vue-router', 'pinia'],
'vant-vendor': ['vant'],
'utils-vendor': ['lodash-es', 'dayjs']
}
}
},
// Compression configuration
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
pure_funcs: ['console.log']
}
}
},
// Development server optimization
server: {
warmup: {
clientFiles: ['./src/components/*.vue']
}
}
})
⚡ Runtime Performance Optimization
Image Optimization Strategy
Lazy Loading Implementation
vue
<script setup>
import { ref, onMounted } from 'vue'
import { Lazyload } from 'vant'
// Image lazy loading configuration
const lazyloadOptions = {
preLoad: 1.3,
error: '/error.png',
loading: '/loading.gif',
attempt: 1
}
onMounted(() => {
app.use(Lazyload, lazyloadOptions)
})
</script>
<template>
<!-- Image lazy loading -->
<img v-lazy="imageUrl" alt="Lazy loaded image" />
<!-- Background image lazy loading -->
<div v-lazy:background-image="bgImageUrl" class="bg-container"></div>
<!-- Vant image component lazy loading -->
<van-image
lazy-load
:src="imageUrl"
width="100"
height="100"
fit="cover"
/>
</template>
Responsive Images
html
<!-- Load different resolution images based on device pixel ratio -->
<img
srcset="image@1x.jpg 1x, image@2x.jpg 2x, image@3x.jpg 3x"
src="image@1x.jpg"
alt="Responsive image"
>
<!-- Use picture element to support multiple formats -->
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="Image">
</picture>
Virtual Scrolling
vue
<script setup>
import { ref, computed, onMounted } from 'vue'
import { List } from 'vant'
const list = ref([])
const loading = ref(false)
const finished = ref(false)
// Virtual scrolling configuration
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
// Simulate loading data
const newItems = Array.from({ length: 20 }, (_, i) => ({
id: list.value.length + i,
title: `Item ${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="No more data"
@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>
🚀 First Screen Loading Optimization
Critical Resource Optimization
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- DNS prefetch -->
<link rel="dns-prefetch" href="//cdn.example.com">
<link rel="dns-prefetch" href="//api.example.com">
<!-- Preload critical resources -->
<link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="/css/critical.css" as="style">
<!-- Preconnect important third-party origins -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<!-- Inline critical CSS -->
<style>
/* Critical first screen styles */
.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 Mobile UI</title>
</head>
<body>
<div id="app">
<!-- First screen loading animation -->
<div class="loading-screen">
<div class="loading-spinner"></div>
</div>
</div>
</body>
</html>
Skeleton Screen Implementation
vue
<script setup>
import { ref, onMounted } from 'vue'
import { Skeleton } from 'vant'
const loading = ref(true)
const data = ref([])
const fetchData = async () => {
// Simulate API request
return new Promise(resolve => {
setTimeout(() => {
resolve([
{ id: 1, title: 'Title 1', value: 'Content 1' },
{ id: 2, title: 'Title 2', value: 'Content 2' },
{ id: 3, title: 'Title 3', value: 'Content 3' }
])
}, 2000)
})
}
onMounted(async () => {
try {
data.value = await fetchData()
} finally {
loading.value = false
}
})
</script>
<template>
<div class="page-container">
<!-- Skeleton screen -->
<van-skeleton
:loading="loading"
:row="3"
:row-width="['100%', '60%', '80%']"
avatar
title
>
<!-- Actual content -->
<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>
📱 Mobile Performance Optimization
Touch Optimization
css
/* Touch delay optimization */
.touch-element {
/* Eliminate 300ms click delay */
touch-action: manipulation;
/* Disable touch highlight */
-webkit-tap-highlight-color: transparent;
/* Disable long press menu */
-webkit-touch-callout: none;
/* Disable text selection */
-webkit-user-select: none;
user-select: none;
}
/* Scroll optimization */
.scroll-container {
/* Enable hardware accelerated scrolling */
-webkit-overflow-scrolling: touch;
overflow-scrolling: touch;
/* Optimize scroll performance */
will-change: scroll-position;
/* Prevent scroll chaining */
overscroll-behavior: contain;
}
/* Long list optimization */
.list-item {
/* Enable GPU acceleration */
transform: translateZ(0);
/* Optimize repainting */
will-change: transform;
}
Memory Optimization
vue
<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
const data = ref([])
const observer = ref(null)
// Clean up timers
const timers = []
const addTimer = (callback, delay) => {
const timer = setTimeout(callback, delay)
timers.push(timer)
return timer
}
// Clean up event listeners
const eventListeners = []
const addEventListener = (element, event, handler) => {
element.addEventListener(event, handler)
eventListeners.push({ element, event, handler })
}
onMounted(() => {
// Use Intersection Observer to optimize scroll performance
observer.value = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Handle when element enters viewport
entry.target.classList.add('visible')
}
})
})
// Observe all list items
nextTick(() => {
document.querySelectorAll('.list-item').forEach(item => {
observer.value.observe(item)
})
})
})
onUnmounted(() => {
// Clean up timers
timers.forEach(timer => clearTimeout(timer))
// Clean up event listeners
eventListeners.forEach(({ element, event, handler }) => {
element.removeEventListener(event, handler)
})
// Clean up Intersection Observer
if (observer.value) {
observer.value.disconnect()
}
})
</script>
📊 Performance Monitoring
Performance Metrics Monitoring
javascript
// Performance monitoring tool
class PerformanceMonitor {
constructor() {
this.metrics = {}
this.init()
}
init() {
this.observePageLoad()
this.observeUserInteraction()
this.observeResourceLoad()
}
// Page load performance
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()
})
}
// User interaction performance
observeUserInteraction() {
// Monitor 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 })
// Monitor 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 })
}
}
// Resource load performance
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 })
}
}
// Report performance data
reportMetrics() {
// Send to analytics service
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))
}
}
}
// Initialize performance monitoring
if (typeof window !== 'undefined') {
new PerformanceMonitor()
}
Web Vitals Monitoring
javascript
// Install web-vitals
// npm install web-vitals
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals'
// Monitor core Web performance metrics
function sendToAnalytics(metric) {
// Send to analytics service
fetch('/api/analytics', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(metric)
})
}
getCLS(sendToAnalytics) // Cumulative Layout Shift
getFID(sendToAnalytics) // First Input Delay
getFCP(sendToAnalytics) // First Contentful Paint
getLCP(sendToAnalytics) // Largest Contentful Paint
getTTFB(sendToAnalytics) // Time to First Byte
🛠️ Debugging Tools
Recommended Performance Analysis Tools
Chrome DevTools
- Performance panel: Analyze runtime performance
- Network panel: Analyze resource loading
- Lighthouse: Comprehensive performance evaluation
Bundle Analyzer
bash# Install npm install --save-dev webpack-bundle-analyzer # Analyze bundle size npm run build -- --analyze
Performance Monitoring Services
- Google Analytics
- Sentry Performance
- New Relic Browser
Performance Optimization Checklist
- [ ] Enable on-demand import to reduce bundle size
- [ ] Configure code splitting to optimize loading speed
- [ ] Implement image lazy loading and compression
- [ ] Use skeleton screens to improve user experience
- [ ] Optimize critical rendering path
- [ ] Enable resource compression and caching
- [ ] Monitor core performance metrics
- [ ] Regular performance testing
📚 Related Resources
- Web Performance Optimization Guide
- Vant Performance Optimization Documentation
- Mobile Adaptation Best Practices
- Theme Customization Complete Guide
- TypeScript Usage Guide
💡 Best Practices Summary
- Bundle size optimization: Use on-demand import and code splitting
- First screen optimization: Implement skeleton screens and critical resource preloading
- Runtime optimization: Use virtual scrolling and image lazy loading
- Mobile optimization: Optimize touch experience and scroll performance
- Performance monitoring: Establish comprehensive performance monitoring system
- Continuous optimization: Regular analysis and optimization of performance bottlenecks
Through the above optimization strategies, you can significantly improve the performance of Vant applications and provide users with a better experience.