Web性能优化完全指南:从加载到渲染的全方位优化

Web性能优化完全指南:从加载到渲染的全方位优化

大家好,我是蔓蔓。性能优化是前端开发中非常重要的一环。今天我来和大家分享Web性能优化的完整指南。

性能指标

Core Web Vitals

javascript 复制代码
const coreWebVitals = {
  LCP: 'Largest Contentful Paint',      // 最大内容绘制 (<=2.5s)
  FID: 'First Input Delay',             // 首次输入延迟 (<=100ms)
  CLS: 'Cumulative Layout Shift'       // 累积布局偏移 (<=0.1)
};

其他指标

javascript 复制代码
const otherMetrics = {
  TTFB: 'Time to First Byte',          // 首字节时间
  FCP: 'First Contentful Paint',       // 首次内容绘制
  TTI: 'Time to Interactive',          // 可交互时间
  TBT: 'Total Blocking Time'           // 总阻塞时间
};

加载优化

资源优化

html 复制代码
<!-- 使用现代图片格式 -->
<picture>
  <source srcset="image.avif" type="image/avif">
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="Image">
</picture>

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

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

<!-- 关键CSS内联 -->
<style>
  .critical {
    /* 关键样式 */
  }
</style>

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

代码分割

javascript 复制代码
// 路由懒加载
const Home = () => import(/* webpackChunkName: "home" */ './pages/Home');
const About = () => import(/* webpackChunkName: "about" */ './pages/About');

// 组件懒加载
const Chart = React.lazy(() => import('./Chart'));

// 条件加载
if (needsFeature) {
  import('./feature').then(module => {
    module.init();
  });
}

缓存策略

javascript 复制代码
// HTTP缓存头
// Cache-Control: max-age=31536000, immutable
// ETag: "123456"
// Last-Modified: Wed, 21 Oct 2023 07:28:00 GMT

// Service Worker缓存
self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((cached) => {
      const fetchPromise = fetch(event.request).then((networkResponse) => {
        caches.open('cache').then((cache) => {
          cache.put(event.request, networkResponse.clone());
        });
        return networkResponse;
      });
      return cached || fetchPromise;
    })
  );
});

运行时优化

渲染优化

css 复制代码
/* 使用transform代替top/left */
.move {
  transform: translateX(100px);
}

/* 使用will-change提示浏览器 */
.will-change {
  will-change: transform, opacity;
}

/* 使用contain隔离渲染 */
.isolated {
  contain: layout paint size;
}

JavaScript优化

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

// 节流
function throttle(fn, limit = 100) {
  let inThrottle = false;
  return function(...args) {
    if (!inThrottle) {
      fn.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// 使用requestAnimationFrame
function animate() {
  // 更新动画
  requestAnimationFrame(animate);
}

内存优化

javascript 复制代码
// 及时清理事件监听器
function cleanup() {
  element.removeEventListener('click', handler);
}

// 避免内存泄漏
class Component {
  destroy() {
    this.timer && clearInterval(this.timer);
    this.observer && this.observer.disconnect();
  }
}

监控与分析

Lighthouse

bash 复制代码
# 运行Lighthouse
lighthouse https://example.com --view

# 生成报告
lighthouse https://example.com --output=json --output-path=report.json

Performance API

javascript 复制代码
// 测量性能
const startTime = performance.now();

// 执行操作
doSomething();

const endTime = performance.now();
console.log(`Time: ${endTime - startTime}ms`);

// 标记和测量
performance.mark('start');
doSomething();
performance.mark('end');
performance.measure('duration', 'start', 'end');

总结

Web性能优化需要从多个层面入手:

  1. 优化资源加载和缓存
  2. 减少渲染阻塞
  3. 优化JavaScript执行
  4. 监控性能指标

技术应当有温度,更快的应用能提升用户体验。

相关推荐
Rocky Ding*2 分钟前
深入浅出Xiaomi-Lens-0技术解析:像素监督如何改变视觉推理
论文阅读·人工智能·深度学习·机器学习·aigc·多模态·ai-native
万岳软件开发小城7 分钟前
AI数字人系统源码如何实现批量视频生成?任务队列与自动化生产流程解析
人工智能·自动化·语音识别·ai数字人小程序·ai数字人系统源码·ai数字人软件开发·ai数字人平台开发
Biomamba生信基地7 分钟前
“AI与生信”公开课,下周五药科大学见
ai·生物信息学
默|笙16 分钟前
【AI应用】认识机器学习与深度学习
人工智能·深度学习·机器学习
TangGeeA16 分钟前
数据库、SQL 与 DB AI
数据库·人工智能·sql
火山引擎开发者社区17 分钟前
案例实践 | 让检索为 Agent 而生:ContextSearch 重构企业售前知识库
人工智能
青蓝智慧马老师19 分钟前
大模型应用落地,到底靠什么?RAG、智能体和上下文工程一次讲清
人工智能
JAVA_AI人工智能项目实战31 分钟前
深度学习实验笔记
人工智能·深度学习·语言模型·自然语言处理
forest_0933 分钟前
当 AI 搜索开始「自我进化」,谁来进化它的核实?——「已核实」结论复核器:3 条结论挖出 2 个洞(附可运行代码)
人工智能·python·机器学习·prompt·agi
金海星科技33 分钟前
船舶交通管理中心的人工智能值守:从“听、说、读、写“看人机协同
人工智能·macos·xcode