Web性能优化进阶指南(续)

十、前端渲染优化

1. 虚拟列表

class VirtualList {
  constructor(options) {
    this.itemHeight = options.itemHeight;
    this.container = options.container;
    this.items = options.items;
    
    this.visibleCount = Math.ceil(container.clientHeight / itemHeight);
    this.startIndex = 0;
    this.endIndex = this.startIndex + this.visibleCount;
    
    this.init();
  }

  init() {
    this.container.addEventListener('scroll', this.onScroll.bind(this));
    this.render();
  }

  render() {
    const fragment = document.createDocumentFragment();
    for(let i = this.startIndex; i < this.endIndex; i++) {
      const item = document.createElement('div');
      item.style.height = `${this.itemHeight}px`;
      item.textContent = this.items[i];
      fragment.appendChild(item);
    }
    this.container.innerHTML = '';
    this.container.appendChild(fragment);
  }
}

// 使用示例
new VirtualList({
  container: document.querySelector('.list-container'),
  itemHeight: 50,
  items: Array.from({length: 10000}, (_, i) => `Item ${i}`)
});

2. requestAnimationFrame优化

class SmoothScroll {
  constructor() {
    this.currentPosition = 0;
    this.targetPosition = 0;
  }

  scrollTo(target) {
    this.targetPosition = target;
    this.animate();
  }

  animate() {
    const distance = this.targetPosition - this.currentPosition;
    const speed = distance * 0.1;
    
    this.currentPosition += speed;
    window.scrollTo(0, this.currentPosition);

    if (Math.abs(distance) > 1) {
      requestAnimationFrame(this.animate.bind(this));
    }
  }
}

十一、内存优化

1. 内存泄漏检测

// 使用Chrome Performance面板检测内存泄漏
class MemoryLeakDetector {
  static startMonitoring() {
    this.intervalId = setInterval(() => {
      console.log('Memory Usage:', performance.memory.usedJSHeapSize);
    }, 1000);
  }

  static stopMonitoring() {
    clearInterval(this.intervalId);
  }
}

// WeakMap使用示例
const cache = new WeakMap();
let object = { data: 'some data' };
cache.set(object, 'cached data');
object = null; // 对象可以被垃圾回收

2. 防抖与节流

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

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

// 使用示例
window.addEventListener('resize', debounce(() => {
  console.log('Window resized');
}, 200));

十二、Worker优化

1. Web Worker

// worker.js
self.addEventListener('message', e => {
  const numbers = e.data;
  const result = numbers.reduce((sum, num) => sum + num, 0);
  self.postMessage(result);
});

// main.js
const worker = new Worker('worker.js');
worker.postMessage([1, 2, 3, 4]);
worker.onmessage = e => {
  console.log('Sum:', e.data);
};

2. Service Worker预缓存

// sw.js
const PRECACHE = 'precache-v1';
const RUNTIME = 'runtime';

// 预缓存资源列表
const PRECACHE_URLS = [
  'index.html',
  './', // 别名 for index.html
  'styles.css',
  'main.js'
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(PRECACHE)
      .then(cache => cache.addAll(PRECACHE_URLS))
      .then(self.skipWaiting())
  );
});

十三、CSS性能优化

1. CSS选择器优化

/* 避免使用通配符 */
/* 不推荐 */
* {
  margin: 0;
  padding: 0;
}

/* 推荐 */
body, h1, h2, h3, p {
  margin: 0;
  padding: 0;
}

/* 避免过度嵌套 */
/* 不推荐 */
.header .nav ul li a {
  color: #333;
}

/* 推荐 */
.nav-link {
  color: #333;
}

2. CSS动画性能

/* 使用transform和opacity进行动画 */
.animate {
  transform: translateX(0);
  opacity: 1;
  transition: transform 0.3s, opacity 0.3s;
  will-change: transform, opacity;
}

.animate:hover {
  transform: translateX(100px);
  opacity: 0.8;
}

十四、webpack优化

1. 分包策略

// webpack.config.js
module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    }
  }
};

2. 动态导入

// 路由级别的代码分割
const routes = [
  {
    path: '/dashboard',
    component: () => import(
      /* webpackChunkName: "dashboard" */
      './views/Dashboard.vue'
    )
  },
  {
    path: '/settings',
    component: () => import(
      /* webpackChunkName: "settings" */
      './views/Settings.vue'
    )
  }
];

十五、监控与分析

1. 性能监控

// 监控关键指标
const performanceMetrics = {
  getFCP() {
    return new Promise(resolve => {
      new PerformanceObserver((entryList) => {
        const entries = entryList.getEntries();
        resolve(entries[entries.length - 1]);
      }).observe({entryTypes: ['paint']});
    });
  },

  getLCP() {
    return new Promise(resolve => {
      new PerformanceObserver((entryList) => {
        const entries = entryList.getEntries();
        resolve(entries[entries.length - 1]);
      }).observe({entryTypes: ['largest-contentful-paint']});
    });
  }
};

2. 错误监控

class ErrorMonitor {
  constructor() {
    this.errors = [];
    this.init();
  }

  init() {
    window.addEventListener('error', this.handleError.bind(this));
    window.addEventListener('unhandledrejection', this.handlePromiseError.bind(this));
  }

  handleError(event) {
    this.errors.push({
      type: 'error',
      message: event.message,
      filename: event.filename,
      line: event.lineno,
      column: event.colno,
      stack: event.error?.stack,
      timestamp: new Date().getTime()
    });
  }

  handlePromiseError(event) {
    this.errors.push({
      type: 'unhandledrejection',
      message: event.reason,
      timestamp: new Date().getTime()
    });
  }
}

官网地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白学过的代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值