前端性能优化完全指南

一、加载性能优化

1. 资源压缩与合并

// webpack配置示例
module.exports = {
  optimization: {
    minimize: true,
    splitChunks: {
      chunks: 'all',
      minSize: 20000,
      minChunks: 1,
      maxAsyncRequests: 30,
      maxInitialRequests: 30,
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          reuseExistingChunk: true,
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
        },
      },
    },
  }
}

2. 图片优化

<!-- 使用webp格式 -->
<picture>
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="图片描述">
</picture>

<!-- 懒加载 -->
<img loading="lazy" src="large-image.jpg" alt="懒加载图片">

<!-- 响应式图片 -->
<img srcset="small.jpg 300w,
             medium.jpg 600w,
             large.jpg 900w"
     sizes="(max-width: 320px) 280px,
            (max-width: 640px) 580px,
            1000px"
     src="medium.jpg" alt="响应式图片">

3. 缓存策略

// Service Worker 缓存示例
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('v1').then(cache => {
      return cache.addAll([
        '/',
        '/styles/main.css',
        '/scripts/main.js',
        '/images/logo.png'
      ]);
    })
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(response => {
      return response || fetch(event.request);
    })
  );
});

二、运行时性能优化

1. DOM操作优化

// 错误示例
for (let i = 0; i < 1000; i++) {
    document.body.innerHTML += '<div>' + i + '</div>';
}

// 优化后
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
    const div = document.createElement('div');
    div.textContent = i;
    fragment.appendChild(div);
}
document.body.appendChild(fragment);

2. 事件委托

// 优化前
document.querySelectorAll('.item').forEach(item => {
    item.addEventListener('click', handleClick);
});

// 优化后
document.querySelector('.list').addEventListener('click', e => {
    if (e.target.matches('.item')) {
        handleClick(e);
    }
});

3. 防抖与节流

// 防抖
function debounce(fn, delay) {
    let timer = null;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
        }, delay);
    };
}

// 节流
function throttle(fn, interval) {
    let last = 0;
    return function (...args) {
        const now = Date.now();
        if (now - last >= interval) {
            last = now;
            fn.apply(this, args);
        }
    };
}

三、React性能优化

1. 避免不必要的渲染

// 使用React.memo
const MyComponent = React.memo(function MyComponent(props) {
    return (
        <div>{props.value}</div>
    );
});

// 使用useMemo
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

// 使用useCallback
const memoizedCallback = useCallback(
    () => {
        doSomething(a, b);
    },
    [a, b],
);

2. 状态管理优化

// 使用useReducer处理复杂状态
function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return {count: state.count + 1};
        case 'decrement':
            return {count: state.count - 1};
        default:
            throw new Error();
    }
}

function Counter() {
    const [state, dispatch] = useReducer(reducer, {count: 0});
    return (
        <>
            Count: {state.count}
            <button onClick={() => dispatch({type: 'increment'})}>+</button>
            <button onClick={() => dispatch({type: 'decrement'})}>-</button>
        </>
    );
}

四、Vue性能优化

1. 大列表优化

// 虚拟滚动组件
<template>
    <div class="virtual-list" @scroll="handleScroll">
        <div class="virtual-list-phantom" :style="{ height: totalHeight + 'px' }">
            <div class="virtual-list-content" :style="{ transform: getTransform }">
                <div class="virtual-list-item" v-for="item in visibleData" :key="item.id">
                    {{ item.content }}
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        listData: {
            type: Array,
            default: () => []
        },
        itemHeight: {
            type: Number,
            default: 50
        }
    },
    computed: {
        visibleData() {
            return this.listData.slice(this.start, this.end);
        },
        getTransform() {
            return `translate3d(0, ${this.offset}px, 0)`;
        }
    },
    methods: {
        handleScroll() {
            // 处理滚动逻辑
        }
    }
}
</script>

2. 按需加载

// 路由懒加载
const router = new VueRouter({
    routes: [
        {
            path: '/user',
            component: () => import('./views/User.vue')
        }
    ]
});

// 组件懒加载
Vue.component('async-component', () => import('./components/AsyncComponent.vue'));

五、网络优化

1. HTTP/2优化

# Nginx配置HTTP/2
server {
    listen 443 ssl http2;
    server_name example.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    
    # 其他配置...
}

2. 预加载关键资源

<!-- 预加载关键CSS -->
<link rel="preload" href="critical.css" as="style">

<!-- 预加载字体 -->
<link rel="preload" href="font.woff2" as="font" crossorigin>

<!-- DNS预解析 -->
<link rel="dns-prefetch" href="//example.com">

六、构建优化

1. webpack优化

// webpack.config.js
module.exports = {
    mode: 'production',
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                parallel: true,
            }),
        ],
        splitChunks: {
            chunks: 'all',
        },
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader'
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin(),
        new CompressionPlugin()
    ]
};

2. Tree Shaking

// package.json
{
    "sideEffects": false
}

// webpack.config.js
module.exports = {
    mode: 'production',
    optimization: {
        usedExports: true,
        sideEffects: true
    }
};

七、监控与分析

1. 性能监控

// 使用Performance API
const observer = new PerformanceObserver((list) => {
    for (const entry of list.getEntries()) {
        console.log('Name: ' + entry.name);
        console.log('Type: ' + entry.entryType);
        console.log('Start: ' + entry.startTime);
        console.log('Duration: ' + entry.duration);
    }
});

observer.observe({entryTypes: ['paint', 'largest-contentful-paint']});

// 自定义性能标记
performance.mark('startProcess');
// 执行一些操作
performance.mark('endProcess');

performance.measure('processTime', 'startProcess', 'endProcess');

2. 错误监控

// 全局错误捕获
window.onerror = function(message, source, lineno, colno, error) {
    console.error('Global error:', {
        message,
        source,
        lineno,
        colno,
        error
    });
    // 上报错误信息
    return true;
};

// Promise错误捕获
window.addEventListener('unhandledrejection', function(event) {
    console.error('Unhandled promise rejection:', event.reason);
    // 上报错误信息
    event.preventDefault();
});

八、最佳实践

1. 代码分割

// 路由级别的代码分割
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

function App() {
    return (
        <Suspense fallback={<div>Loading...</div>}>
            <Switch>
                <Route exact path="/" component={Home}/>
                <Route path="/about" component={About}/>
            </Switch>
        </Suspense>
    );
}

2. 资源优先级控制

<!-- 关键CSS内联 -->
<style>
    /* 关键渲染路径CSS */
</style>

<!-- 非关键CSS异步加载 -->
<link rel="preload" href="non-critical.css" as="style" onload="this.rel='stylesheet'">

<!-- JavaScript异步加载 -->
<script defer src="app.js"></script>

这篇文章涵盖了前端性能优化的多个关键领域:

  1. 加载性能优化
  2. 运行时性能优化
  3. React性能优化
  4. Vue性能优化
  5. 网络优化
  6. 构建优化
  7. 监控与分析
  8. 最佳实践
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐