前端性能优化完全指南

加载性能优化

资源压缩和优化

// Webpack配置示例
module.exports = {
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin(), // 压缩JavaScript
            new CssMinimizerPlugin(), // 压缩CSS
            new ImageMinimizerPlugin({ // 压缩图片
                minimizer: {
                    implementation: ImageMinimizerPlugin.imageminMinify,
                    options: {
                        plugins: [
                            ['mozjpeg', { quality: 80 }],
                            ['pngquant', { quality: [0.6, 0.8] }],
                            ['svgo', { plugins: ['removeViewBox'] }]
                        ]
                    }
                }
            })
        ]
    }
};

代码分割和懒加载

// React懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));

// Vue懒加载
const LazyComponent = () => import('./LazyComponent.vue');

// 动态导入
const loadModule = async () => {
    const module = await import('./heavy-module.js');
    module.initialize();
};

渲染性能优化

避免重绘和重排

// 不好的做法:引起多次重排
const element = document.getElementById('my-element');
element.style.width = '100px';
element.style.height = '100px';
element.style.left = '10px';
element.style.top = '10px';

// 好的做法:使用requestAnimationFrame
const element = document.getElementById('my-element');
requestAnimationFrame(() => {
    element.style.cssText = `
        width: 100px;
        height: 100px;
        left: 10px;
        top: 10px;
    `;
});

虚拟列表优化

// 只渲染可见区域的内容
class VirtualList {
    constructor(container, itemHeight, totalItems, renderItem) {
        this.container = container;
        this.itemHeight = itemHeight;
        this.totalItems = totalItems;
        this.renderItem = renderItem;
        this.visibleItems = Math.ceil(container.clientHeight / itemHeight);
        this.startIndex = 0;
        
        this.init();
    }
    
    init() {
        this.container.style.position = 'relative';
        this.container.style.height = `${this.totalItems * this.itemHeight}px`;
        
        // 监听滚动事件
        this.container.addEventListener('scroll', () => {
            this.startIndex = Math.floor(this.container.scrollTop / this.itemHeight);
            this.renderVisibleItems();
        });
        
        this.renderVisibleItems();
    }
    
    renderVisibleItems() {
        // 渲染可见项...
    }
}