10、前端性能优化

33 阅读4分钟

1、代码优化

减少DOM操作

示例:

// 避免频繁的DOM操作
for (let i = 0; i < 1000; i++) {
    const div = document.createElement('div');
    div.textContent = `Item ${i}`;
    document.body.appendChild(div);
}

// 使用DocumentFragment减少DOM操作
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
    const div = document.createElement('div');
    div.textContent = `Item ${i}`;
    fragment.appendChild(div);
}
document.body.appendChild(fragment);

减少重排和重绘

示例:

// 对元素样式进行多次操作,导致多次重排
element.style.width = '100px';
element.style.height = '100px';
element.style.backgroundColor = 'red';

// 合并操作,减少重排
element.style.cssText = 'width: 100px; height: 100px; background-color: red;';

使用Debounce和Throttle

示例:

// Debounce函数
function debounce(fn, delay) {
    let timeout;
    return function() {
        clearTimeout(timeout);
        timeout = setTimeout(fn, delay);
    }
}

// Throttle函数
function throttle(fn, limit) {
    let lastCall = 0;
    return function() {
        const now = (new Date()).getTime();
        if (now - lastCall >= limit) {
            lastCall = now;
            fn();
        }
    }
}

// 使用Debounce限制resize事件
window.addEventListener('resize', debounce(() => {
    console.log('Window resized');
}, 250));

// 使用Throttle限制scroll事件
window.addEventListener('scroll', throttle(() => {
    console.log('Window scrolled');
}, 200));

异步加载JavaScript

示例:

<!-- 使用async属性 -->
<script src="script.js" async></script>

<!-- 使用defer属性 -->
<script src="script.js" defer></script>

<!-- 放置在页面底部 -->
<body>
    <!-- 内容 -->
    <script src="script.js"></script>
</body>

代码拆分

示例:

// 使用动态导入按需加载模块
document.getElementById('loadButton').addEventListener('click', () => {
    import('./module.js').then(module => {
        module.init();
    });
});

2、服务器优化

使用CDN

示例:

<!-- 使用CDN加载静态资源 -->
<link rel="stylesheet" href="https://cdn.example.com/style.css">
<script src="https://cdn.example.com/script.js" defer></script>

开启Gzip压缩

示例:

# 在Apache中开启Gzip压缩
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>

# 在Nginx中开启Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

使用HTTP/2

示例:

# 在Nginx中启用HTTP/2
server {
    listen 443 ssl http2;
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    ...
}

设置合适的缓存策略

示例:

# 设置Cache-Control头
<FilesMatch ".(html|css|js|png|jpg|jpeg|gif|svg|ico)$">
    Header set Cache-Control "max-age=31536000, public"
</FilesMatch>

# 使用ETag
FileETag MTime Size

资源优化

图片优化

示例:

<!-- 使用响应式图片 -->
<img srcset="small.jpg 480w, medium.jpg 768w, large.jpg 1024w" src="large.jpg" alt="Example Image">

字体优化

示例:

/* 使用系统字体 */
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 使用font-display属性改进字体加载 */
@font-face {
    font-family: 'CustomFont';
    src: url('customfont.woff2') format('woff2');
    font-display: swap;
}

减少HTTP请求

示例:

/* 使用CSS sprits合并图标 */
.icon {
    background-image: url('sprites.png');
}

.icon-home {
    background-position: 0 0;
}

.icon-user {
    background-position: -20px 0;
}

使用合并和压缩

示例:

// 使用Webpack进行资源管理
const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /.css$/,
                use: ['style-loader', 'css-loader']
            }
        ]
    },
    optimization: {
        minimize: true
    }
};

3、工具和库

Webpack

Webpack 是一个强大的模块打包工具,用于将现代 JavaScript 应用程序的模块按照依赖关系打包成一个或多个文件。它支持多种资源(如 JavaScript、CSS、图片等)的处理和优化。

功能

  1. 代码拆分:按需加载模块,减少初始加载时间。
  2. 资源压缩:压缩 JavaScript、CSS 等资源,减少文件大小。
  3. 模块热替换:在开发过程中实时替换模块,无需刷新页面。
  4. 插件和Loader:支持各种插件和 loader,扩展功能,处理不同类型的文件。

示例

const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /.css$/,
                use: ['style-loader', 'css-loader']
            }
        ]
    },
    optimization: {
        minimize: true  // 启用资源压缩
    }
};

Lighthouse

Lighthouse 是 Google 提供的开源工具,用于分析网页性能与质量。它可以生成一份详尽的报告,提供从性能到可访问性、安全性等多方面的改进建议。

功能

  1. 性能分析:测量页面加载速度和渲染时间。
  2. PWA 检测:检测页面是否符合渐进式网络应用(PWA)的标准。
  3. SEO 检测:检查页面是否符合基本的 SEO 标准。
  4. 可访问性检测:提供有关页面可访问性的改进建议。
  5. 最佳实践:建议适用于网络应用的开发最佳实践。

使用方法

通过 Chrome DevTools 或者命令行运行 Lighthouse 分析网页性能。

# 使用npx运行Lighthouse
npx lighthouse https://www.example.com --view

或通过 Chrome DevTools 查看 Lighthouse 报告:

  1. 打开 Chrome DevTools(F12)。
  2. 选择“Lighthouse”面板。
  3. 点击“Generate report”按钮。

Chrome DevTools

Chrome DevTools 是 Chrome 浏览器中提供的一组 Web 开发工具,可以用来查看和调试网页。它提供了多种功能,帮助开发者检测和优化网页性能。

功能

  1. Elements:查看与操作 HTML 和 CSS。
  2. Console:查看和执行 JavaScript 命令。
  3. Network:分析网络请求,查看加载时间和请求大小。
  4. Performance:记录和分析页面加载和运行的性能信息。
  5. Memory:查看内存使用情况,检测内存泄漏。
  6. Application:管理和调试 Service Workers、Local Storage 等。

使用方法

  1. 打开 Chrome DevTools(F12 或右键点击页面并选择“检查”)。
  2. 切换到不同的面板(如 Elements, Console, Network)以查看和分析网页的不同方面。
  3. 使用 Network 面板分析所有资源的加载情况。
  4. 在 Performance 面板记录和分析页面的性能表现。

示例

  • 查看网络请求: 打开 Network 面板,在页面加载时查看所有网络请求的列表,包括类型、大小、时间等信息。
  • 记录性能分析: 打开 Performance 面板,点击“Record”按钮,执行用户操作,然后停止记录,查看详细的性能分析报告。

通过这些工具和库,你可以全面分析和优化前端性能,提升用户体验。