🚀 前端性能优化面试题金典:从入门到精通

154 阅读9分钟

让面试官刮目相看的前端性能优化深度解析


其他面试链接

# 前端面试必刷!50道HTML+CSS高频面试题详解

# JavaScript面试必刷!50道核心概念+ES6+新特性详解

# Vue面试必刷!从入门到精通,一文搞定Vue2/Vue3核心知识

# React面试题目详解:从入门到精通,这些题你都会吗?

#浏览器原理+网络知识面试必刷!50道高频面试题详解

📋 目录


基础篇:性能优化核心概念

1. 🌟 Web Vitals 深度解析

面试题: 请详细解释 Core Web Vitals 的三个核心指标,并说明如何优化每个指标?

参考答案:

LCP (Largest Contentful Paint) - 最大内容绘制

  • 定义: 页面加载过程中最大可见元素渲染完成的时间
  • 优化策略:
    // 1. 图片懒加载优化
    const imageObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = entry.target;
          img.src = img.dataset.src;
          imageObserver.unobserve(img);
        }
      });
    });
    
    // 2. 关键资源预加载
    <link rel="preload" href="critical.css" as="style">
    <link rel="preload" href="hero-image.jpg" as="image">
    

FID (First Input Delay) - 首次输入延迟

  • 定义: 用户首次与页面交互到浏览器响应该交互的时间
  • 优化策略:
    // 代码分割和懒加载
    const LazyComponent = React.lazy(() => import('./HeavyComponent'));
    
    // 任务调度优化
    const scheduler = {
      tasks: [],
      addTask(task) {
        this.tasks.push(task);
        this.schedule();
      },
      schedule() {
        if (this.tasks.length > 0) {
          requestIdleCallback(() => {
            const task = this.tasks.shift();
            task();
            if (this.tasks.length > 0) {
              this.schedule();
            }
          });
        }
      }
    };
    

CLS (Cumulative Layout Shift) - 累积布局偏移

  • 定义: 页面加载过程中意外布局偏移的累积分数
  • 优化策略:
    /* 为动态内容预留空间 */
    .dynamic-content {
      min-height: 200px; /* 防止内容加载时的布局偏移 */
    }
    
    /* 字体加载优化 */
    @font-face {
      font-family: 'CustomFont';
      font-display: swap; /* 避免字体加载时的布局偏移 */
    }
    

2. 🎯 渲染性能优化

面试题: 解释浏览器渲染流程,并说明如何优化每个阶段?

参考答案:

浏览器渲染流程

  1. 解析HTML → DOM树
  2. 解析CSS → CSSOM树
  3. 合并 → 渲染树(Render Tree)
  4. 布局 → 计算元素位置和大小
  5. 绘制 → 填充像素
  6. 合成 → 合成层处理

优化策略

// 1. 减少重排重绘
// ❌ 错误做法
element.style.width = '100px';
element.style.height = '100px';
element.style.left = '10px';

// ✅ 正确做法
element.style.cssText = 'width: 100px; height: 100px; left: 10px;';

// 2. 使用 transform 和 opacity 触发合成层
.element {
  transform: translateZ(0); /* 强制创建合成层 */
  will-change: transform; /* 提示浏览器优化 */
}

// 3. 批量DOM操作
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
  const div = document.createElement('div');
  fragment.appendChild(div);
}
container.appendChild(fragment);

3. 📦 资源加载优化

面试题: 如何优化网页的资源加载性能?请从多个维度分析。

参考答案:

图片优化

<!-- 响应式图片 -->
<picture>
  <source media="(min-width: 800px)" srcset="large.jpg">
  <source media="(min-width: 400px)" srcset="medium.jpg">
  <img src="small.jpg" alt="响应式图片">
</picture>

<!-- WebP格式支持 -->
<picture>
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="WebP图片">
</picture>

字体优化

/* 字体子集化 */
@font-face {
  font-family: 'CustomFont';
  src: url('font-subset.woff2') format('woff2');
  font-display: swap;
  unicode-range: U+0000-00FF; /* 只加载需要的字符 */
}

代码分割

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

// 组件级别的代码分割
const HeavyComponent = lazy(() => 
  import('./HeavyComponent').then(module => ({
    default: module.HeavyComponent
  }))
);

进阶篇:现代浏览器优化技术

4. 🔄 Service Worker 与缓存策略

面试题: 设计一个完整的 Service Worker 缓存策略,包括离线支持和缓存更新机制。

参考答案:

// service-worker.js
const CACHE_NAME = 'app-cache-v1';
const STATIC_CACHE = 'static-cache-v1';
const DYNAMIC_CACHE = 'dynamic-cache-v1';

// 缓存策略
const cacheStrategies = {
  // 缓存优先策略
  cacheFirst: async (request) => {
    const cachedResponse = await caches.match(request);
    if (cachedResponse) {
      return cachedResponse;
    }
    const networkResponse = await fetch(request);
    const cache = await caches.open(STATIC_CACHE);
    cache.put(request, networkResponse.clone());
    return networkResponse;
  },

  // 网络优先策略
  networkFirst: async (request) => {
    try {
      const networkResponse = await fetch(request);
      const cache = await caches.open(DYNAMIC_CACHE);
      cache.put(request, networkResponse.clone());
      return networkResponse;
    } catch (error) {
      const cachedResponse = await caches.match(request);
      return cachedResponse || new Response('离线内容', {
        status: 503,
        statusText: 'Service Unavailable'
      });
    }
  },

  // 仅网络策略
  networkOnly: async (request) => {
    return await fetch(request);
  }
};

// Service Worker 安装
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(STATIC_CACHE).then((cache) => {
      return cache.addAll([
        '/',
        '/static/css/main.css',
        '/static/js/main.js',
        '/static/images/logo.png'
      ]);
    })
  );
});

// 请求拦截
self.addEventListener('fetch', (event) => {
  const { request } = event;
  const url = new URL(request.url);

  // 静态资源使用缓存优先
  if (url.pathname.startsWith('/static/')) {
    event.respondWith(cacheStrategies.cacheFirst(request));
  }
  // API请求使用网络优先
  else if (url.pathname.startsWith('/api/')) {
    event.respondWith(cacheStrategies.networkFirst(request));
  }
  // 其他请求仅网络
  else {
    event.respondWith(cacheStrategies.networkOnly(request));
  }
});

5. 🎨 CSS 性能优化

面试题: 现代CSS性能优化有哪些最佳实践?请提供具体的代码示例。

参考答案:

CSS-in-JS 性能优化

// 使用 styled-components 的优化技巧
import styled, { css } from 'styled-components';

// 1. 避免在渲染中创建样式对象
const Button = styled.button`
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  
  // 使用 CSS 变量提高性能
  background-color: var(--button-bg, #007bff);
  color: var(--button-color, white);
  
  // 使用 will-change 提示浏览器优化
  will-change: transform;
  
  &:hover {
    transform: translateY(-2px);
    transition: transform 0.2s ease;
  }
`;

// 2. 条件样式优化
const ConditionalButton = styled.button`
  ${props => props.primary && css`
    background-color: #007bff;
    color: white;
  `}
  
  ${props => props.large && css`
    padding: 15px 30px;
    font-size: 18px;
  `}
`;

CSS 关键路径优化

/* 内联关键CSS */
<style>
  /* 首屏关键样式 */
  .hero-section {
    height: 100vh;
    background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>

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

6. 🚀 JavaScript 性能优化

面试题: 如何优化JavaScript代码的执行性能?包括内存管理和执行效率。

参考答案:

内存管理优化

// 1. 避免内存泄漏
class ComponentManager {
  constructor() {
    this.components = new Map();
    this.cleanup = new Set();
  }

  addComponent(id, component) {
    this.components.set(id, component);
    
    // 注册清理函数
    this.cleanup.add(() => {
      component.destroy?.();
      this.components.delete(id);
    });
  }

  destroy() {
    this.cleanup.forEach(cleanup => cleanup());
    this.cleanup.clear();
    this.components.clear();
  }
}

// 2. 使用 WeakMap 和 WeakSet
const componentCache = new WeakMap();
const processedComponents = new WeakSet();

function processComponent(component) {
  if (processedComponents.has(component)) {
    return componentCache.get(component);
  }
  
  const result = expensiveOperation(component);
  componentCache.set(component, result);
  processedComponents.add(component);
  
  return result;
}

// 3. 防抖和节流优化
function debounce(func, wait, immediate = false) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      timeout = null;
      if (!immediate) func.apply(this, args);
    };
    
    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    
    if (callNow) func.apply(this, args);
  };
}

function throttle(func, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

执行效率优化

// 1. 使用 Web Workers 处理计算密集型任务
// main.js
const worker = new Worker('worker.js');

worker.postMessage({ type: 'CALCULATE', data: largeDataSet });

worker.onmessage = function(e) {
  const { type, result } = e.data;
  if (type === 'CALCULATE_COMPLETE') {
    updateUI(result);
  }
};

// worker.js
self.onmessage = function(e) {
  const { type, data } = e.data;
  
  if (type === 'CALCULATE') {
    const result = performHeavyCalculation(data);
    self.postMessage({ type: 'CALCULATE_COMPLETE', result });
  }
};

// 2. 使用 requestAnimationFrame 优化动画
function smoothAnimation(element, targetValue, duration) {
  const startValue = parseFloat(getComputedStyle(element).left);
  const startTime = performance.now();
  
  function animate(currentTime) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    
    // 使用缓动函数
    const easeProgress = easeInOutCubic(progress);
    const currentValue = startValue + (targetValue - startValue) * easeProgress;
    
    element.style.left = currentValue + 'px';
    
    if (progress < 1) {
      requestAnimationFrame(animate);
    }
  }
  
  requestAnimationFrame(animate);
}

function easeInOutCubic(t) {
  return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
}

高级篇:架构与工程化优化

7. 🏗️ 微前端架构性能优化

面试题: 在微前端架构中,如何优化应用间的通信和资源加载性能?

参考答案:

微前端通信优化

// 1. 使用 CustomEvent 进行应用间通信
class MicroFrontendBus {
  constructor() {
    this.listeners = new Map();
  }

  emit(eventName, data) {
    const event = new CustomEvent(eventName, {
      detail: data,
      bubbles: true
    });
    document.dispatchEvent(event);
  }

  on(eventName, callback) {
    if (!this.listeners.has(eventName)) {
      this.listeners.set(eventName, []);
    }
    this.listeners.get(eventName).push(callback);
    
    document.addEventListener(eventName, callback);
  }

  off(eventName, callback) {
    const callbacks = this.listeners.get(eventName) || [];
    const index = callbacks.indexOf(callback);
    if (index > -1) {
      callbacks.splice(index, 1);
      document.removeEventListener(eventName, callback);
    }
  }
}

// 2. 共享依赖优化
class SharedDependencyManager {
  constructor() {
    this.sharedModules = new Map();
  }

  async loadSharedModule(moduleName) {
    if (this.sharedModules.has(moduleName)) {
      return this.sharedModules.get(moduleName);
    }

    const module = await import(`/shared/${moduleName}.js`);
    this.sharedModules.set(moduleName, module);
    return module;
  }
}

资源预加载策略

// 微前端资源预加载
class MicroFrontendPreloader {
  constructor() {
    this.preloadedApps = new Set();
    this.preloadQueue = [];
  }

  async preloadApp(appName) {
    if (this.preloadedApps.has(appName)) {
      return;
    }

    const appConfig = await this.getAppConfig(appName);
    
    // 预加载关键资源
    await Promise.all([
      this.preloadScript(appConfig.script),
      this.preloadStyles(appConfig.styles),
      this.preloadAssets(appConfig.assets)
    ]);

    this.preloadedApps.add(appName);
  }

  async preloadScript(scriptUrl) {
    return new Promise((resolve, reject) => {
      const link = document.createElement('link');
      link.rel = 'preload';
      link.as = 'script';
      link.href = scriptUrl;
      link.onload = resolve;
      link.onerror = reject;
      document.head.appendChild(link);
    });
  }
}

8. 🔧 构建工具优化

面试题: 如何优化现代前端构建工具的性能?包括 Vite、Webpack 等。

参考答案:

Vite 优化配置

// vite.config.js
import { defineConfig } from 'vite';
import { resolve } from 'path';

export default defineConfig({
  // 开发服务器优化
  server: {
    hmr: {
      overlay: false // 禁用错误覆盖层提高性能
    },
    fs: {
      strict: false // 允许访问工作区外的文件
    }
  },

  // 构建优化
  build: {
    // 代码分割策略
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          utils: ['lodash', 'moment'],
          ui: ['antd', '@ant-design/icons']
        }
      }
    },
    
    // 压缩优化
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  },

  // 依赖预构建优化
  optimizeDeps: {
    include: ['react', 'react-dom', 'antd'],
    exclude: ['@vite/client', '@vite/env']
  },

  // CSS 优化
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/styles/variables.scss";`
      }
    }
  }
});

Webpack 5 优化配置

// webpack.config.js
const path = require('path');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = {
  // 模块解析优化
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      'react': path.resolve(__dirname, 'node_modules/react'),
      'react-dom': path.resolve(__dirname, 'node_modules/react-dom')
    },
    extensions: ['.js', '.jsx', '.ts', '.tsx']
  },

  // 缓存优化
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename]
    }
  },

  // 代码分割优化
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        },
        common: {
          name: 'common',
          minChunks: 2,
          chunks: 'all',
          enforce: true
        }
      }
    }
  },

  // 插件优化
  plugins: [
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      openAnalyzer: false
    })
  ]
};

实战篇:性能监控与调试

9. 📊 性能监控系统

面试题: 设计一个完整的前端性能监控系统,包括数据收集、分析和报警。

参考答案:

性能数据收集

// performance-monitor.js
class PerformanceMonitor {
  constructor() {
    this.metrics = {};
    this.init();
  }

  init() {
    this.collectWebVitals();
    this.collectResourceMetrics();
    this.collectErrorMetrics();
    this.collectUserMetrics();
  }

  // Web Vitals 收集
  collectWebVitals() {
    // LCP
    new PerformanceObserver((entryList) => {
      const entries = entryList.getEntries();
      const lastEntry = entries[entries.length - 1];
      this.metrics.lcp = lastEntry.startTime;
    }).observe({ entryTypes: ['largest-contentful-paint'] });

    // FID
    new PerformanceObserver((entryList) => {
      const entries = entryList.getEntries();
      entries.forEach(entry => {
        this.metrics.fid = entry.processingStart - entry.startTime;
      });
    }).observe({ entryTypes: ['first-input'] });

    // CLS
    let clsValue = 0;
    new PerformanceObserver((entryList) => {
      const entries = entryList.getEntries();
      entries.forEach(entry => {
        if (!entry.hadRecentInput) {
          clsValue += entry.value;
        }
      });
      this.metrics.cls = clsValue;
    }).observe({ entryTypes: ['layout-shift'] });
  }

  // 资源加载监控
  collectResourceMetrics() {
    const resources = performance.getEntriesByType('resource');
    this.metrics.resources = resources.map(resource => ({
      name: resource.name,
      duration: resource.duration,
      size: resource.transferSize,
      type: this.getResourceType(resource.name)
    }));
  }

  // 错误监控
  collectErrorMetrics() {
    window.addEventListener('error', (event) => {
      this.metrics.errors = this.metrics.errors || [];
      this.metrics.errors.push({
        message: event.message,
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno,
        stack: event.error?.stack,
        timestamp: Date.now()
      });
    });

    window.addEventListener('unhandledrejection', (event) => {
      this.metrics.errors = this.metrics.errors || [];
      this.metrics.errors.push({
        type: 'unhandledrejection',
        reason: event.reason,
        timestamp: Date.now()
      });
    });
  }

  // 用户行为监控
  collectUserMetrics() {
    // 页面停留时间
    let startTime = Date.now();
    window.addEventListener('beforeunload', () => {
      this.metrics.timeOnPage = Date.now() - startTime;
    });

    // 用户交互
    ['click', 'scroll', 'keydown'].forEach(eventType => {
      document.addEventListener(eventType, (event) => {
        this.metrics.userInteractions = this.metrics.userInteractions || [];
        this.metrics.userInteractions.push({
          type: eventType,
          target: event.target.tagName,
          timestamp: Date.now()
        });
      });
    });
  }

  // 数据上报
  report() {
    const reportData = {
      url: window.location.href,
      userAgent: navigator.userAgent,
      timestamp: Date.now(),
      ...this.metrics
    };

    // 使用 sendBeacon 确保数据可靠传输
    if (navigator.sendBeacon) {
      navigator.sendBeacon('/api/performance', JSON.stringify(reportData));
    } else {
      fetch('/api/performance', {
        method: 'POST',
        body: JSON.stringify(reportData),
        keepalive: true
      });
    }
  }
}

// 使用示例
const monitor = new PerformanceMonitor();

// 页面卸载时上报数据
window.addEventListener('beforeunload', () => {
  monitor.report();
});

10. 🐛 性能调试工具

面试题: 如何调试前端性能问题?请提供一套完整的调试工具和方法。

参考答案:

自定义性能调试工具

// performance-debugger.js
class PerformanceDebugger {
  constructor() {
    this.marks = new Map();
    this.measures = new Map();
    this.init();
  }

  init() {
    // 监听所有性能标记
    new PerformanceObserver((entryList) => {
      const entries = entryList.getEntries();
      entries.forEach(entry => {
        if (entry.entryType === 'mark') {
          this.marks.set(entry.name, entry.startTime);
        } else if (entry.entryType === 'measure') {
          this.measures.set(entry.name, entry.duration);
        }
      });
    }).observe({ entryTypes: ['mark', 'measure'] });
  }

  // 标记性能点
  mark(name) {
    performance.mark(name);
    console.log(`🔖 Mark: ${name} at ${performance.now().toFixed(2)}ms`);
  }

  // 测量性能区间
  measure(name, startMark, endMark) {
    performance.measure(name, startMark, endMark);
    const measure = performance.getEntriesByName(name)[0];
    console.log(`📏 Measure: ${name} = ${measure.duration.toFixed(2)}ms`);
  }

  // 分析渲染性能
  analyzeRenderPerformance() {
    const paintEntries = performance.getEntriesByType('paint');
    const navigationEntries = performance.getEntriesByType('navigation');
    
    console.group('🎨 渲染性能分析');
    paintEntries.forEach(entry => {
      console.log(`${entry.name}: ${entry.startTime.toFixed(2)}ms`);
    });
    
    if (navigationEntries.length > 0) {
      const nav = navigationEntries[0];
      console.log(`DOM加载完成: ${nav.domContentLoadedEventEnd - nav.domContentLoadedEventStart}ms`);
      console.log(`页面完全加载: ${nav.loadEventEnd - nav.loadEventStart}ms`);
    }
    console.groupEnd();
  }

  // 内存使用分析
  analyzeMemoryUsage() {
    if (performance.memory) {
      console.group('🧠 内存使用分析');
      console.log(`已使用堆内存: ${(performance.memory.usedJSHeapSize / 1024 / 1024).toFixed(2)}MB`);
      console.log(`总堆内存: ${(performance.memory.totalJSHeapSize / 1024 / 1024).toFixed(2)}MB`);
      console.log(`堆内存限制: ${(performance.memory.jsHeapSizeLimit / 1024 / 1024).toFixed(2)}MB`);
      console.groupEnd();
    }
  }

  // 网络性能分析
  analyzeNetworkPerformance() {
    const resources = performance.getEntriesByType('resource');
    const slowResources = resources.filter(resource => resource.duration > 1000);
    
    console.group('🌐 网络性能分析');
    console.log(`总资源数: ${resources.length}`);
    console.log(`慢资源数 (>1s): ${slowResources.length}`);
    
    if (slowResources.length > 0) {
      console.log('慢资源列表:');
      slowResources.forEach(resource => {
        console.log(`  ${resource.name}: ${resource.duration.toFixed(2)}ms`);
      });
    }
    console.groupEnd();
  }

  // 生成性能报告
  generateReport() {
    console.group('📊 性能调试报告');
    this.analyzeRenderPerformance();
    this.analyzeMemoryUsage();
    this.analyzeNetworkPerformance();
    
    console.log('📈 性能标记:');
    this.marks.forEach((time, name) => {
      console.log(`  ${name}: ${time.toFixed(2)}ms`);
    });
    
    console.log('📏 性能测量:');
    this.measures.forEach((duration, name) => {
      console.log(`  ${name}: ${duration.toFixed(2)}ms`);
    });
    
    console.groupEnd();
  }
}

// 使用示例
const debugger = new PerformanceDebugger();

// 在关键代码处添加标记
debugger.mark('component-start');
// ... 组件渲染代码 ...
debugger.mark('component-end');
debugger.measure('component-render', 'component-start', 'component-end');

// 生成完整报告
setTimeout(() => {
  debugger.generateReport();
}, 5000);

前沿篇:新兴技术与趋势

11. 🌐 WebAssembly 性能优化

面试题: 如何在前端项目中使用 WebAssembly 来提升性能?请提供实际应用场景。

参考答案:

WebAssembly 集成示例

// wasm-loader.js
class WASMLoader {
  constructor() {
    this.modules = new Map();
  }

  async loadWASMModule(modulePath, imports = {}) {
    if (this.modules.has(modulePath)) {
      return this.modules.get(modulePath);
    }

    try {
      const wasmModule = await WebAssembly.instantiateStreaming(
        fetch(modulePath),
        imports
      );
      
      this.modules.set(modulePath, wasmModule);
      return wasmModule;
    } catch (error) {
      console.error('WASM加载失败:', error);
      throw error;
    }
  }
}

// 图像处理示例
class ImageProcessor {
  constructor() {
    this.wasmLoader = new WASMLoader();
    this.wasmModule = null;
  }

  async init() {
    this.wasmModule = await this.wasmLoader.loadWASMModule('/wasm/image-processor.wasm', {
      env: {
        memory: new WebAssembly.Memory({ initial: 256 }),
        console_log: (ptr, len) => {
          const bytes = new Uint8Array(this.wasmModule.instance.exports.memory.buffer, ptr, len);
          console.log(new TextDecoder().decode(bytes));
        }
      }
    });
  }

  async processImage(imageData) {
    if (!this.wasmModule) {
      await this.init();
    }

    const { instance } = this.wasmModule;
    const { memory, process_image, get_result } = instance.exports;

    // 将图像数据复制到WASM内存
    const dataPtr = instance.exports.alloc(imageData.length);
    const dataArray = new Uint8Array(memory.buffer, dataPtr, imageData.length);
    dataArray.set(imageData);

    // 调用WASM函数处理图像
    const resultPtr = process_image(dataPtr, imageData.length);
    
    // 获取处理结果
    const resultArray = new Uint8Array(memory.buffer, resultPtr, imageData.length);
    const result = new Uint8Array(resultArray);

    // 释放内存
    instance.exports.dealloc(dataPtr);
    instance.exports.dealloc(resultPtr);

    return result;
  }
}

12. 🚀 边缘计算优化

面试题: 如何利用边缘计算来优化前端性能?包括CDN、Edge Functions等。

参考答案:

Edge Function 示例

// edge-function.js (Cloudflare Workers)
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);
  
  // 动态内容优化
  if (url.pathname.startsWith('/api/')) {
    return handleAPIRequest(request);
  }
  
  // 静态资源优化
  if (url.pathname.match(/\.(js|css|png|jpg|jpeg|gif|svg)$/)) {
    return handleStaticAsset(request);
  }
  
  // 页面请求
  return handlePageRequest(request);
}

async function handleAPIRequest(request) {
  // 边缘缓存策略
  const cache = caches.default;
  const cacheKey = new Request(request.url, request);
  let response = await cache.match(cacheKey);
  
  if (!response) {
    // 从源服务器获取数据
    response = await fetch(request);
    
    // 设置缓存头
    response = new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers: {
        ...response.headers,
        'Cache-Control': 'public, max-age=300', // 5分钟缓存
        'CDN-Cache-Control': 'public, max-age=3600' // CDN缓存1小时
      }
    });
    
    // 存储到边缘缓存
    event.waitUntil(cache.put(cacheKey, response.clone()));
  }
  
  return response;
}

async function handleStaticAsset(request) {
  const cache = caches.default;
  let response = await cache.match(request);
  
  if (!response) {
    response = await fetch(request);
    
    // 静态资源长期缓存
    response = new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers: {
        ...response.headers,
        'Cache-Control': 'public, max-age=31536000', // 1年缓存
        'CDN-Cache-Control': 'public, max-age=31536000'
      }
    });
    
    event.waitUntil(cache.put(request, response.clone()));
  }
  
  return response;
}

🎯 面试技巧总结

回答性能优化问题的框架

  1. 问题分析:首先分析性能瓶颈的具体原因
  2. 解决方案:提供多种优化策略和具体实现
  3. 效果评估:说明优化后的预期效果和衡量指标
  4. 权衡考虑:分析不同方案的优缺点和适用场景

常见面试问题准备

  • 基础概念:Web Vitals、渲染流程、缓存策略
  • 实践技能:代码优化、工具使用、问题排查
  • 架构思维:性能监控、系统设计、技术选型
  • 前沿技术:WebAssembly、边缘计算、新兴标准

加分项

  • 能够结合实际项目经验
  • 了解性能优化的最新趋势
  • 具备完整的性能监控和调试能力
  • 能够从用户体验角度思考问题

📚 延伸阅读


这份面试题金典涵盖了前端性能优化的各个方面,从基础概念到前沿技术,帮助你在面试中脱颖而出! 🚀