Skip to content

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:

  1. Reduce first-screen data loading, use pagination or lazy loading
  2. Optimize page structure, reduce unnecessary component nesting
  3. Use skeleton screens to improve user experience
  4. 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:

  1. Use uni.preloadPage() to preload pages (supported on some platforms only)
  2. Reduce computation during page initialization
  3. Use page caching mechanism to avoid recreating pages
  4. 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:

  1. 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>
  2. Implement pagination loading using loadmore event
  3. Reduce complexity of list items, avoid deep nesting
  4. 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:

  1. 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);
  2. Batch update data, avoid frequent small updates
  3. Use nextTick to delay update operations
  4. 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:

  1. Compress images, use mobile-friendly image formats (like WebP)
  2. 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>
  3. Use image thumbnails, show low-quality images first, then load high-quality images
  4. Use CDN to accelerate image loading
  5. 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:

  1. Control the number of simultaneously loaded images
  2. Release unused image resources promptly
  3. Use image cache management strategy
  4. 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:

  1. Merge requests to reduce request count
  2. Implement request queue to control concurrent request count
  3. Use data caching to avoid duplicate requests for same data
  4. 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:

  1. Set reasonable cache expiration time
  2. Implement cache update mechanism, actively update cache after critical operations
  3. Use version numbers or timestamps to mark cached data
  4. 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:

  1. Split complex components into multiple simple components
  2. Use computed properties to cache complex calculation results
  3. Avoid complex calculations in templates
  4. 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:

  1. Use v-if and v-show appropriately: use v-show for frequent toggling, v-if for conditional rendering
  2. Avoid unnecessary data binding
  3. Use Object.freeze() to freeze large data objects that don't need reactivity:
    js
    data() {
      return {
        // Freeze large static data to avoid Vue creating reactivity
        staticData: Object.freeze(largeStaticData)
      }
    }
  4. 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:

  1. Avoid creating functions or objects in loops
  2. Use Web Workers for time-consuming calculations (supported on some platforms only)
  3. Optimize algorithms and data structures, reduce time complexity
  4. Avoid frequent DOM operations, batch DOM updates
  5. Use requestAnimationFrame to optimize animation effects:
    js
    function 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:

  1. Clean up unused event listeners promptly:
    js
    // Clean up event listeners when component is destroyed
    onBeforeUnmount() {
      uni.offPullDownRefresh();
      document.removeEventListener('visibilitychange', this.handleVisibilityChange);
    }
  2. Avoid creating too many closures
  3. Use weak references (WeakMap, WeakSet) to store object references
  4. 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:

  1. Reduce resources and code loaded at startup
  2. 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"]
        }
      ]
    }
  3. Delay loading of non-critical features
  4. 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:

  1. Remove unused components and libraries
  2. Compress code and resource files
  3. Use on-demand loading, avoid full import of large libraries
  4. Use smaller alternative libraries
  5. 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:

  1. Follow Mini Program best practices and limitations
  2. Use subpackage loading to reduce main package size
  3. Use custom components appropriately
  4. Avoid frequent setData, merge data updates

Q: H5 platform performance issues

Problem Description: Specific performance issues encountered on H5 platform.

Solutions:

  1. Use browser developer tools to analyze performance bottlenecks
  2. Optimize first-screen loading speed, consider server-side rendering
  3. Use Web Workers for complex calculations
  4. Implement resource preloading and caching strategies

Q: App platform performance issues

Problem Description: Specific performance issues encountered on App platform.

Solutions:

  1. Use native components to improve performance
  2. Optimize native plugin usage
  3. Set window and page styles appropriately to reduce rendering burden
  4. Optimize separately for Android and iOS platforms

Performance Monitoring and Analysis

How to Monitor Application Performance

  1. 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);
    }
  2. Monitor response time of key user interactions
  3. Collect and analyze user device performance data
  4. Use third-party performance monitoring services

Performance Optimization Best Practices

  1. Design Phase:

    • Design reasonable data structures and state management
    • Plan component splitting and reuse strategies
    • Consider performance differences across devices
  2. Development Phase:

    • Follow performance optimization principles
    • Conduct regular performance testing
    • Use performance analysis tools to identify bottlenecks
  3. Testing Phase:

    • Test performance on various devices
    • Test under weak network conditions
    • Conduct stress testing and limit testing
  4. 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.

一次开发,多端部署 - 让跨平台开发更简单