Performance Optimization Issues
This page collects common issues and solutions for uni-app application performance optimization.
Page Loading Optimization
Q: Slow initial page loading
Problem Description: Application startup or initial page loading takes too long.
Solutions:
- Reduce first-screen data loading, use pagination or lazy loading
- Optimize page structure, reduce unnecessary component nesting
- Use skeleton screens to improve user experience
- Preload critical resources:js
// Preload in App.vue onLaunch onLaunch() { // Preload data needed for next page uni.request({ url: 'api/data', success: (res) => { getApp().globalData.preloadData = res.data; } }); }
Q: Page transition stuttering
Problem Description: Obvious stuttering when navigating between pages.
Solutions:
- Use
uni.preloadPage()
to preload pages (supported on some platforms only) - Reduce computation during page initialization
- Use page caching mechanism to avoid recreating pages
- Optimize page animation effects, use simple transition animations
List Performance Optimization
Q: Long list scrolling stuttering
Problem Description: Lists containing large amounts of data stutter when scrolling.
Solutions:
- Use virtual lists, only render elements in visible area:vue
<recycle-list :list="longList" :height="listHeight"> <template v-slot:item="{ item }"> <view class="list-item">{{ item.title }}</view> </template> </recycle-list>
- Implement pagination loading using
loadmore
event - Reduce complexity of list items, avoid deep nesting
- Use
wx:key
or:key
to optimize list updates
Q: Frequent list data updates causing stuttering
Problem Description: Frequent list data updates cause interface stuttering.
Solutions:
- Use debounce or throttle techniques to limit update frequency:js
function debounce(fn, delay) { let timer = null; return function() { if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, arguments); }, delay); }; } // Use debounce to update list const updateList = debounce(function() { this.list = newList; }, 200);
- Batch update data, avoid frequent small updates
- Use
nextTick
to delay update operations - Consider using Vuex for state management to optimize data flow
Image Optimization
Q: Slow image loading affecting page experience
Problem Description: Images on the page load slowly, affecting overall experience.
Solutions:
- Compress images, use mobile-friendly image formats (like WebP)
- Use lazy loading, only load images in visible area:vue
<image v-for="item in imageList" :key="item.id" :lazy-load="true" :src="item.url"> </image>
- Use image thumbnails, show low-quality images first, then load high-quality images
- Use CDN to accelerate image loading
- Preload critical image resources
Q: Large number of images causing high memory usage
Problem Description: After loading many images, memory usage is high and may cause crashes.
Solutions:
- Control the number of simultaneously loaded images
- Release unused image resources promptly
- Use image cache management strategy
- Dynamically adjust image quality based on device performance:js
// Adjust image quality based on device performance const systemInfo = uni.getSystemInfoSync(); const imageQuality = systemInfo.benchmarkLevel > 5 ? 'high' : 'low';
Network Request Optimization
Q: Too many network requests causing performance degradation
Problem Description: Large number of network requests on the page causing performance degradation.
Solutions:
- Merge requests to reduce request count
- Implement request queue to control concurrent request count
- Use data caching to avoid duplicate requests for same data
- Optimize request timing, avoid simultaneous multiple requests:js
// Request queue management class RequestQueue { constructor(maxConcurrent = 5) { this.queue = []; this.running = 0; this.maxConcurrent = maxConcurrent; } add(requestFn) { return new Promise((resolve, reject) => { this.queue.push({ requestFn, resolve, reject }); this.run(); }); } run() { if (this.running >= this.maxConcurrent || this.queue.length === 0) { return; } const { requestFn, resolve, reject } = this.queue.shift(); this.running++; requestFn() .then(resolve) .catch(reject) .finally(() => { this.running--; this.run(); }); } } // Use request queue const requestQueue = new RequestQueue(3); requestQueue.add(() => uni.request({ url: 'api/data1' })); requestQueue.add(() => uni.request({ url: 'api/data2' }));
Q: Improper data caching strategy causing data inconsistency
Problem Description: After using cache, data updates are not timely or inconsistent.
Solutions:
- Set reasonable cache expiration time
- Implement cache update mechanism, actively update cache after critical operations
- Use version numbers or timestamps to mark cached data
- Provide manual refresh functionality, allow users to force data updates
Rendering Performance Optimization
Q: Complex components render slowly
Problem Description: Components with complex logic or many elements render slowly.
Solutions:
- Split complex components into multiple simple components
- Use computed properties to cache complex calculation results
- Avoid complex calculations in templates
- Use
v-once
directive to render static content:vue<view v-once> <!-- This content will only render once --> <complex-static-content></complex-static-content> </view>
Q: Frequent re-rendering causing stuttering
Problem Description: Frequent component updates causing page stuttering.
Solutions:
- Use
v-if
andv-show
appropriately: usev-show
for frequent toggling,v-if
for conditional rendering - Avoid unnecessary data binding
- Use
Object.freeze()
to freeze large data objects that don't need reactivity:jsdata() { return { // Freeze large static data to avoid Vue creating reactivity staticData: Object.freeze(largeStaticData) } }
- Use debounce and throttle to limit update frequency
JavaScript Performance Optimization
Q: Low JavaScript execution efficiency
Problem Description: JavaScript code executes slowly, affecting interaction response speed.
Solutions:
- Avoid creating functions or objects in loops
- Use Web Workers for time-consuming calculations (supported on some platforms only)
- Optimize algorithms and data structures, reduce time complexity
- Avoid frequent DOM operations, batch DOM updates
- Use
requestAnimationFrame
to optimize animation effects:jsfunction animateElement() { // Update element position this.position += 1; // Continue next frame animation if (this.position < 100) { requestAnimationFrame(animateElement.bind(this)); } } // Start animation requestAnimationFrame(animateElement.bind(this));
Q: Memory leak issues
Problem Description: Memory usage continues to increase after long application runtime.
Solutions:
- Clean up unused event listeners promptly:js
// Clean up event listeners when component is destroyed onBeforeUnmount() { uni.offPullDownRefresh(); document.removeEventListener('visibilitychange', this.handleVisibilityChange); }
- Avoid creating too many closures
- Use weak references (WeakMap, WeakSet) to store object references
- Regularly check and release large objects
Startup Performance Optimization
Q: Long application cold start time
Problem Description: Long time from clicking app icon to interactive state.
Solutions:
- Reduce resources and code loaded at startup
- Use subpackage loading (Mini Program platforms):js
// Configure subpackages in pages.json { "pages": [ // Main package pages ], "subPackages": [ { "root": "pages/feature1", "pages": ["index", "detail"] }, { "root": "pages/feature2", "pages": ["index", "detail"] } ] }
- Delay loading of non-critical features
- Optimize startup page design, provide visual feedback
Q: Application size too large
Problem Description: Application installation package is too large, affecting download and installation speed.
Solutions:
- Remove unused components and libraries
- Compress code and resource files
- Use on-demand loading, avoid full import of large libraries
- Use smaller alternative libraries
- Optimize images and media resources:js
// Configure image compression in vue.config.js module.exports = { chainWebpack: config => { config.module .rule('images') .use('image-webpack-loader') .loader('image-webpack-loader') .options({ bypassOnDebug: true }) .end(); } }
Platform-Specific Optimization
Q: Mini Program platform performance issues
Problem Description: Specific performance issues encountered on Mini Program platforms.
Solutions:
- Follow Mini Program best practices and limitations
- Use subpackage loading to reduce main package size
- Use custom components appropriately
- Avoid frequent setData, merge data updates
Q: H5 platform performance issues
Problem Description: Specific performance issues encountered on H5 platform.
Solutions:
- Use browser developer tools to analyze performance bottlenecks
- Optimize first-screen loading speed, consider server-side rendering
- Use Web Workers for complex calculations
- Implement resource preloading and caching strategies
Q: App platform performance issues
Problem Description: Specific performance issues encountered on App platform.
Solutions:
- Use native components to improve performance
- Optimize native plugin usage
- Set window and page styles appropriately to reduce rendering burden
- Optimize separately for Android and iOS platforms
Performance Monitoring and Analysis
How to Monitor Application Performance
- Use custom performance tracking:js
// Page loading performance monitoring onLoad() { this.startTime = Date.now(); } onReady() { const loadTime = Date.now() - this.startTime; console.log(`Page load time: ${loadTime}ms`); // Report performance data reportPerformance('pageLoad', loadTime); }
- Monitor response time of key user interactions
- Collect and analyze user device performance data
- Use third-party performance monitoring services
Performance Optimization Best Practices
Design Phase:
- Design reasonable data structures and state management
- Plan component splitting and reuse strategies
- Consider performance differences across devices
Development Phase:
- Follow performance optimization principles
- Conduct regular performance testing
- Use performance analysis tools to identify bottlenecks
Testing Phase:
- Test performance on various devices
- Test under weak network conditions
- Conduct stress testing and limit testing
Post-Release:
- Monitor online performance metrics
- Collect user feedback
- Continuous optimization and iteration
If you cannot find a solution to your problem on this page, please check the uni-app official documentation or ask questions on the uni-app official forum.