Appearance
网络性能优化
网络性能优化是提升应用程序响应速度和用户体验的关键。本章将详细介绍各种网络性能优化技术和最佳实践。
HTTP 协议优化
HTTP/2 优化
javascript
// 1. Node.js HTTP/2 服务器配置
const http2 = require('http2');
const fs = require('fs');
const path = require('path');
// HTTP/2 服务器配置
class Http2Server {
constructor() {
this.options = {
key: fs.readFileSync(path.join(__dirname, '../ssl/server.key')),
cert: fs.readFileSync(path.join(__dirname, '../ssl/server.crt')),
// 启用 ALPN 协商
allowHTTP1: true,
};
}
createServer(handler) {
const server = http2.createSecureServer(this.options);
server.on('error', (err) => console.error(err));
server.on('stream', (stream, headers) => {
// 启用服务器推送
if (headers[':path'] === '/') {
// 推送关键资源
stream.pushStream({ ':path': '/css/main.css' }, (err, pushStream) => {
if (!err) {
pushStream.respond({
'content-type': 'text/css',
':status': 200
});
pushStream.end(fs.readFileSync(path.join(__dirname, '../public/css/main.css')));
}
});
stream.pushStream({ ':path': '/js/main.js' }, (err, pushStream) => {
if (!err) {
pushStream.respond({
'content-type': 'application/javascript',
':status': 200
});
pushStream.end(fs.readFileSync(path.join(__dirname, '../public/js/main.js')));
}
});
}
// 处理原始请求
handler(stream, headers);
});
return server;
}
}
// 2. HTTP/2 客户端实现
class Http2Client {
constructor(origin) {
this.session = http2.connect(origin);
this.session.on('error', (err) => console.error('HTTP/2 session error:', err));
}
async request(headers, data = null) {
return new Promise((resolve, reject) => {
const req = this.session.request(headers);
let response = '';
req.setEncoding('utf8');
req.on('data', (chunk) => {
response += chunk;
});
req.on('end', () => {
resolve({
statusCode: req.statusCode,
headers: req.headers,
data: response
});
});
req.on('error', reject);
if (data) {
req.write(data);
}
req.end();
});
}
close() {
this.session.close();
}
}
// 3. HTTP/2 性能优化配置
const http2Optimizations = {
// 多路复用优化
multiplexing: {
maxConcurrentStreams: 100, // 最大并发流数
streamPriority: true, // 启用流优先级
},
// 服务器推送配置
serverPush: {
enabled: true,
criticalAssets: [
'/css/main.css',
'/js/main.js',
'/images/logo.png'
],
pushPolicy: 'critical-first' // 优先推送关键资源
},
// 头部压缩优化
headerCompression: {
useHPACK: true, // 使用 HPACK 压缩
staticTableSize: 4096,
dynamicTableSize: 4096
}
};
HTTP/3 和 QUIC
javascript
// 1. QUIC/HTTP/3 基础配置
// 注意:Node.js 目前对 HTTP/3 支持有限,这里展示概念性代码
class QuicServer {
constructor() {
// QUIC 连接配置
this.quicConfig = {
// 连接迁移
connectionMigration: true,
// 0-RTT 支持
zeroRtt: true,
// 流控制
streamControl: {
maxStreamsBidi: 100,
maxStreamsUni: 100,
maxStreamData: 1024 * 1024 // 1MB
},
// 拥塞控制
congestionControl: {
algorithm: 'cubic', // 或 'reno', 'bbr'
initialWindow: 10,
minimumWindow: 2
}
};
}
// 2. 连接建立优化
async establishConnection(clientInfo) {
// 实现 QUIC 连接建立逻辑
return {
connectionId: this.generateConnectionId(),
transportParameters: this.getTransportParameters(),
encryptionKeys: await this.deriveEncryptionKeys(clientInfo)
};
}
generateConnectionId() {
const crypto = require('crypto');
return crypto.randomBytes(8).toString('hex');
}
getTransportParameters() {
return {
idleTimeout: 30000, // 30秒空闲超时
maxPacketSize: 1200, // 最大包大小
ackDelayExponent: 3,
maxAckDelay: 25,
disableMigration: false
};
}
async deriveEncryptionKeys(clientInfo) {
// 实现密钥派生逻辑
return {
initialKey: await this.deriveInitialKey(clientInfo),
handshakeKey: await this.deriveHandshakeKey(clientInfo),
oneRttKey: await this.deriveOneRttKey(clientInfo)
};
}
async deriveInitialKey(clientInfo) {
// 使用 ChaCha20-Poly1305 或 AES-GCM
return 'derived_initial_key';
}
async deriveHandshakeKey(clientInfo) {
return 'derived_handshake_key';
}
async deriveOneRttKey(clientInfo) {
return 'derived_onertt_key';
}
}
CDN 和缓存优化
CDN 配置优化
javascript
// 1. CDN 策略配置
class CdnConfiguration {
constructor() {
this.strategies = {
// 静态资源策略
static: {
cacheTime: '1y', // 1年缓存
compression: true,
edgeLocations: ['US', 'EU', 'APAC'],
fallbackOrigin: 'primary-origin.example.com'
},
// 动态内容策略
dynamic: {
cacheTime: '5m', // 5分钟缓存
varyHeaders: ['Accept-Encoding', 'Accept-Language'],
staleWhileRevalidate: 86400 // 1天
},
// API 内容策略
api: {
cacheTime: '1m', // 1分钟缓存
authPassthrough: true,
queryParamHandling: 'whitelist',
allowedQueryParams: ['page', 'limit', 'sort']
}
};
}
// 2. 资源版本控制
generateResourceUrl(resourcePath, version) {
const baseUrl = 'https://cdn.example.com';
const resourceVersion = version || this.getCurrentVersion();
return `${baseUrl}${resourcePath}?v=${resourceVersion}`;
}
getCurrentVersion() {
// 可以从构建系统获取版本号
return process.env.BUILD_VERSION || 'latest';
}
// 3. 智能缓存头设置
setCacheHeaders(res, resourceType) {
switch(resourceType) {
case 'static':
res.set({
'Cache-Control': 'public, max-age=31536000, immutable', // 1年
'ETag': this.generateETag(res),
'Vary': 'Accept-Encoding'
});
break;
case 'semi-static':
res.set({
'Cache-Control': 'public, max-age=604800', // 1周
'ETag': this.generateETag(res),
'Vary': 'Accept-Encoding'
});
break;
case 'dynamic':
res.set({
'Cache-Control': 'private, max-age=300', // 5分钟
'Pragma': 'no-cache'
});
break;
default:
res.set({
'Cache-Control': 'no-cache, no-store, must-revalidate'
});
}
}
generateETag(res) {
const crypto = require('crypto');
const content = res.getHeader('content-length') || Date.now().toString();
return `"${crypto.createHash('md5').update(content).digest('hex')}"`;
}
}
// 4. CDN 预热和刷新
class CdnManager {
constructor(apiClient) {
this.apiClient = apiClient;
}
// 预热资源
async warmResources(resources) {
const promises = resources.map(resource =>
this.apiClient.purgeCache(resource, { type: 'prefetch' })
);
return await Promise.allSettled(promises);
}
// 刷新资源
async refreshResources(resources) {
const promises = resources.map(resource =>
this.apiClient.purgeCache(resource, { type: 'invalidate' })
);
return await Promise.allSettled(promises);
}
// 智能预热
async intelligentWarm() {
// 基于访问模式预热热门资源
const hotResources = await this.getHotResources();
return await this.warmResources(hotResources);
}
async getHotResources() {
// 实现热门资源获取逻辑
return [
'/css/main.css',
'/js/main.js',
'/images/logo.png',
'/fonts/main.woff2'
];
}
}
浏览器缓存策略
javascript
// 1. HTTP 缓存策略
class BrowserCacheStrategy {
constructor() {
this.strategies = {
// 长期缓存(版本化资源)
'immutable': {
headers: {
'Cache-Control': 'public, immutable, max-age=31536000'
}
},
// 会话缓存
'session': {
headers: {
'Cache-Control': 'public, max-age=86400' // 1天
}
},
// 短期缓存
'short': {
headers: {
'Cache-Control': 'public, max-age=3600' // 1小时
}
},
// 无缓存
'no-cache': {
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
}
}
};
}
// 2. ETag 实现
generateETag(content, algorithm = 'md5') {
const crypto = require('crypto');
const hash = crypto.createHash(algorithm);
hash.update(content);
return `"${hash.digest('hex')}"`;
}
// 3. 条件请求处理
handleConditionalRequest(req, res, resourceInfo) {
const ifNoneMatch = req.headers['if-none-match'];
const ifModifiedSince = req.headers['if-modified-since'];
if (ifNoneMatch && ifNoneMatch === resourceInfo.etag) {
res.status(304).end();
return true;
}
if (ifModifiedSince &&
new Date(ifModifiedSince) >= new Date(resourceInfo.lastModified)) {
res.status(304).end();
return true;
}
return false;
}
// 4. Service Worker 缓存策略
generateServiceWorkerScript() {
return `
const CACHE_NAME = 'app-v${Date.now()}';
const urlsToCache = [
'/',
'/css/main.css',
'/js/main.js',
'/images/logo.png'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(urlsToCache))
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
// 返回缓存,否则发起网络请求
return response || fetch(event.request);
})
);
});
`;
}
}
// 5. 缓存分层策略
class MultiLayerCache {
constructor() {
this.layers = {
// L1: 内存缓存
memory: new Map(),
// L2: Redis 缓存
redis: null, // 需要初始化
// L3: 数据库缓存
database: null // 需要初始化
};
}
async get(key) {
// L1: 检查内存缓存
if (this.layers.memory.has(key)) {
return this.layers.memory.get(key);
}
// L2: 检查 Redis 缓存
if (this.layers.redis) {
const redisValue = await this.layers.redis.get(key);
if (redisValue) {
// 同步到内存缓存
this.layers.memory.set(key, redisValue);
return redisValue;
}
}
// L3: 检查数据库缓存
if (this.layers.database) {
const dbValue = await this.layers.database.get(key);
if (dbValue) {
// 同步到内存和 Redis 缓存
this.layers.memory.set(key, dbValue);
if (this.layers.redis) {
await this.layers.redis.set(key, dbValue, 'EX', 3600); // 1小时
}
return dbValue;
}
}
return null;
}
async set(key, value, ttl = 3600) {
// 设置所有层级的缓存
this.layers.memory.set(key, value);
if (this.layers.redis) {
await this.layers.redis.set(key, value, 'EX', ttl);
}
if (this.layers.database) {
await this.layers.database.set(key, value, ttl);
}
}
}
网络传输优化
压缩和编码
javascript
// 1. 内容压缩策略
const compression = require('compression');
const express = require('express');
const app = express();
// 全局压缩中间件
app.use(compression({
// 只压缩大于 1KB 的响应
threshold: 1024,
// 压缩级别 (0-9, 9 是最高压缩率)
level: 6,
// 压缩策略
strategy: compression.Z_DEFAULT_STRATEGY,
// 自定义过滤函数
filter: (req, res) => {
// 不压缩已经压缩过的响应
if (req.headers['x-no-compression']) {
return false;
}
// 使用默认过滤器
return compression.filter(req, res);
}
}));
// 2. Brotli 压缩 (更高压缩率)
const expressBrotli = require('express-brotli');
app.use(expressBrotli());
// 3. 图片优化
class ImageOptimizer {
constructor() {
this.supportedFormats = ['webp', 'avif', 'jpeg', 'png'];
this.qualitySettings = {
webp: 85,
jpeg: 80,
png: 9
};
}
// 根据客户端支持选择最佳格式
negotiateImageFormat(req) {
const acceptHeader = req.headers.accept || '';
// 优先级:AVIF > WebP > JPEG/PNG
if (acceptHeader.includes('image/avif')) {
return 'avif';
} else if (acceptHeader.includes('image/webp')) {
return 'webp';
} else if (acceptHeader.includes('image/jpeg')) {
return 'jpeg';
} else if (acceptHeader.includes('image/png')) {
return 'png';
}
return 'jpeg'; // 默认格式
}
// 响应式图片生成
generateResponsiveImages(imagePath, sizes = [320, 640, 1024, 1920]) {
return sizes.map(size => ({
src: `${imagePath}?width=${size}`,
width: size,
descriptor: `${size}w`
}));
}
// 图片压缩配置
getCompressionOptions(format) {
return {
quality: this.qualitySettings[format],
progressive: true,
optimize: true
};
}
}
// 4. 文本压缩优化
class TextCompressor {
constructor() {
this.compressionLibraries = {
gzip: require('zlib').createGzip,
deflate: require('zlib').createDeflate,
brotli: require('zlib').createBrotliCompress
};
}
async compressText(text, algorithm = 'gzip') {
const compressor = this.compressionLibraries[algorithm]();
return new Promise((resolve, reject) => {
let compressed = Buffer.alloc(0);
compressor.on('data', chunk => {
compressed = Buffer.concat([compressed, chunk]);
});
compressor.on('end', () => resolve(compressed));
compressor.on('error', reject);
compressor.write(text);
compressor.end();
});
}
// 压缩级别选择
getOptimalCompressionLevel(contentType, contentLength) {
if (contentLength < 1024) {
// 小文件使用快速压缩
return 1;
} else if (contentType.includes('text') || contentType.includes('javascript')) {
// 文本内容使用高压缩率
return 9;
} else {
// 二进制内容使用中等压缩
return 6;
}
}
}
资源加载优化
javascript
// 1. 资源预加载策略
class ResourcePreloader {
constructor() {
this.preloadStrategies = {
// DNS 预解析
'dns-prefetch': {
pattern: /^https?:\/\//,
priority: 'low'
},
// 预连接
'preconnect': {
pattern: /^https:\/\/api\./,
priority: 'medium'
},
// 资源预加载
'preload': {
pattern: /\.(css|js|woff2|jpg|png)$/,
priority: 'high'
},
// 资源预获取
'prefetch': {
pattern: /^\/next-page/,
priority: 'low'
}
};
}
generatePreloadLinks(resources) {
const links = [];
resources.forEach(resource => {
const strategy = this.getPreloadStrategy(resource.url);
if (strategy) {
links.push(this.createPreloadLink(resource, strategy));
}
});
return links;
}
getPreloadStrategy(url) {
for (const [type, config] of Object.entries(this.preloadStrategies)) {
if (config.pattern.test(url)) {
return { type, ...config };
}
}
return null;
}
createPreloadLink(resource, strategy) {
const link = {
rel: strategy.type,
href: resource.url
};
if (strategy.type === 'preload') {
link.as = this.getResourceType(resource.url);
if (resource.media) link.media = resource.media;
if (resource.crossorigin) link.crossorigin = resource.crossorigin;
}
return link;
}
getResourceType(url) {
const extension = url.split('.').pop().toLowerCase();
const typeMap = {
'css': 'style',
'js': 'script',
'woff': 'font',
'woff2': 'font',
'ttf': 'font',
'eot': 'font',
'jpg': 'image',
'jpeg': 'image',
'png': 'image',
'gif': 'image',
'svg': 'image',
'webp': 'image'
};
return typeMap[extension] || 'fetch';
}
}
// 2. 资源加载优先级
class PriorityBasedLoader {
constructor() {
this.priorityQueue = {
high: [], // 关键资源
medium: [], // 重要资源
low: [] // 可选资源
};
this.loadingStates = {
'idle': 0,
'loading': 1,
'loaded': 2,
'error': 3
};
}
addResource(url, priority = 'medium', options = {}) {
const resource = {
url,
priority,
options,
state: this.loadingStates.idle,
startTime: null,
endTime: null
};
this.priorityQueue[priority].push(resource);
return resource;
}
async loadCriticalResources() {
// 首先加载高优先级资源
const highPriority = this.priorityQueue.high;
const promises = highPriority.map(resource => this.loadResource(resource));
await Promise.all(promises);
}
async loadResource(resource) {
resource.state = this.loadingStates.loading;
resource.startTime = Date.now();
try {
const response = await fetch(resource.url, resource.options);
resource.state = this.loadingStates.loaded;
resource.endTime = Date.now();
resource.duration = resource.endTime - resource.startTime;
return response;
} catch (error) {
resource.state = this.loadingStates.error;
resource.endTime = Date.now();
resource.error = error;
throw error;
}
}
// 智能加载(根据网络状况调整)
async intelligentLoad() {
const connection = navigator.connection || {};
const effectiveType = connection.effectiveType || '4g';
let concurrentLoads;
switch(effectiveType) {
case 'slow-2g':
concurrentLoads = 1;
break;
case '2g':
concurrentLoads = 2;
break;
case '3g':
concurrentLoads = 3;
break;
default:
concurrentLoads = 6; // 4g/wifi
}
// 按优先级和网络状况加载资源
return this.loadWithConcurrencyLimit(concurrentLoads);
}
async loadWithConcurrencyLimit(limit) {
const allResources = [
...this.priorityQueue.high,
...this.priorityQueue.medium,
...this.priorityQueue.low
];
const semaphore = new Semaphore(limit);
const promises = allResources.map(async (resource) => {
await semaphore.acquire();
try {
return await this.loadResource(resource);
} finally {
semaphore.release();
}
});
return await Promise.all(promises);
}
}
// 信号量实现
class Semaphore {
constructor(maxConcurrency) {
this.maxConcurrency = maxConcurrency;
this.currentConcurrency = 0;
this.queue = [];
}
async acquire() {
return new Promise((resolve) => {
if (this.currentConcurrency < this.maxConcurrency) {
this.currentConcurrency++;
resolve();
} else {
this.queue.push(() => {
this.currentConcurrency++;
resolve();
});
}
});
}
release() {
this.currentConcurrency--;
if (this.queue.length > 0) {
const next = this.queue.shift();
next();
}
}
}
网络监控和分析
性能监控
javascript
// 1. 网络性能监控
class NetworkPerformanceMonitor {
constructor() {
this.metrics = {
dnsLookup: 0,
tcpConnection: 0,
requestStart: 0,
responseStart: 0,
responseEnd: 0,
loadEventEnd: 0
};
this.histograms = {
responseTime: new Histogram(),
bandwidth: new Histogram(),
throughput: new Histogram()
};
}
// 2. Resource Timing API 监控
measureResourceTiming(url) {
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
if (entry.name === url) {
this.recordResourceMetrics(entry);
}
});
});
observer.observe({ entryTypes: ['resource'] });
// 触发资源加载
this.loadResource(url);
}
recordResourceMetrics(entry) {
const metrics = {
// DNS 查询时间
dnsTime: entry.domainLookupEnd - entry.domainLookupStart,
// TCP 连接时间
tcpTime: entry.connectEnd - entry.connectStart,
// SSL/TLS 协商时间
sslTime: entry.secureConnectionStart > 0
? entry.connectEnd - entry.secureConnectionStart
: 0,
// 请求时间
requestTime: entry.responseStart - entry.requestStart,
// 响应时间
responseTime: entry.responseEnd - entry.responseStart,
// 总时间
totalTime: entry.responseEnd - entry.startTime,
// 传输大小
encodedBodySize: entry.encodedBodySize,
decodedBodySize: entry.decodedBodySize,
// 服务器处理时间
serverTime: entry.responseStart - entry.requestStart
};
this.reportMetrics(metrics);
}
reportMetrics(metrics) {
// 发送指标到监控系统
console.log('Resource Metrics:', metrics);
// 更新直方图
this.histograms.responseTime.update(metrics.totalTime);
this.histograms.bandwidth.update(this.calculateBandwidth(metrics));
this.histograms.throughput.update(this.calculateThroughput(metrics));
}
calculateBandwidth(metrics) {
if (metrics.totalTime === 0) return 0;
return (metrics.decodedBodySize * 8) / (metrics.totalTime / 1000); // bps
}
calculateThroughput(metrics) {
if (metrics.totalTime === 0) return 0;
return metrics.decodedBodySize / (metrics.totalTime / 1000); // Bps
}
// 3. 网络连接监控
monitorNetworkQuality() {
if ('connection' in navigator) {
const connection = navigator.connection;
const networkInfo = {
effectiveType: connection.effectiveType, // 'slow-2g', '2g', '3g', '4g'
downlink: connection.downlink, // Mbps
rtt: connection.rtt, // ms
saveData: connection.saveData // boolean
};
console.log('Network Info:', networkInfo);
this.reportNetworkInfo(networkInfo);
}
}
reportNetworkInfo(info) {
// 发送到监控服务
fetch('/api/network-metrics', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
timestamp: Date.now(),
...info
})
}).catch(err => console.error('Failed to send network metrics:', err));
}
// 4. 自定义网络探测
async measureLatency(host, port = 80, timeout = 5000) {
const start = Date.now();
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(`http://${host}:${port}/ping`, {
signal: controller.signal,
method: 'HEAD'
});
clearTimeout(timeoutId);
const latency = Date.now() - start;
return { success: true, latency, status: response.status };
} catch (error) {
clearTimeout(timeoutId);
return { success: false, error: error.message };
}
}
async measureBandwidth(url, duration = 10000) {
const start = Date.now();
let bytesDownloaded = 0;
try {
const response = await fetch(url);
const reader = response.body.getReader();
let done = false;
while (!done) {
const { value, done: readerDone } = await reader.read();
done = readerDone;
if (value) {
bytesDownloaded += value.length;
}
if (Date.now() - start >= duration) {
break;
}
}
const elapsed = Date.now() - start;
const bandwidth = (bytesDownloaded * 8) / (elapsed / 1000); // bps
return {
success: true,
bandwidth,
bytesDownloaded,
duration: elapsed
};
} catch (error) {
return { success: false, error: error.message };
}
}
}
// 5. 简单的直方图实现
class Histogram {
constructor(buckets = [10, 50, 100, 500, 1000, 5000]) {
this.buckets = buckets;
this.counts = new Array(buckets.length + 1).fill(0); // +1 for +Inf bucket
this.sum = 0;
this.count = 0;
}
update(value) {
let bucketIndex = this.buckets.findIndex(threshold => value <= threshold);
if (bucketIndex === -1) {
bucketIndex = this.buckets.length; // +Inf bucket
}
this.counts[bucketIndex]++;
this.sum += value;
this.count++;
}
getPercentile(percentile) {
if (this.count === 0) return 0;
const targetCount = Math.floor((percentile / 100) * this.count);
let currentCount = 0;
for (let i = 0; i < this.counts.length; i++) {
currentCount += this.counts[i];
if (currentCount >= targetCount) {
return i < this.buckets.length ? this.buckets[i] : Infinity;
}
}
return this.buckets[this.buckets.length - 1];
}
}
实际优化案例
电商网站网络优化案例
javascript
// 电商网站网络性能优化实现
class EcommerceNetworkOptimizer {
constructor() {
this.preloader = new ResourcePreloader();
this.loader = new PriorityBasedLoader();
this.monitor = new NetworkPerformanceMonitor();
this.cdnManager = new CdnManager(/* api client */);
this.imageOptimizer = new ImageOptimizer();
this.cacheStrategy = new BrowserCacheStrategy();
this.init();
}
async init() {
// 1. 启动网络监控
this.monitor.monitorNetworkQuality();
// 2. 预热 CDN 资源
await this.cdnManager.intelligentWarm();
// 3. 设置性能监控
this.setupPerformanceMonitoring();
}
// 首页加载优化
async optimizeHomePage() {
// 识别关键资源
const criticalResources = [
{ url: '/css/critical.css', priority: 'high' },
{ url: '/js/main.js', priority: 'high' },
{ url: '/api/hero-content', priority: 'high' },
{ url: '/images/hero-banner.jpg', priority: 'high' }
];
// 添加到加载队列
criticalResources.forEach(resource => {
this.loader.addResource(resource.url, resource.priority);
});
// 预加载次要资源
const secondaryResources = [
'/css/product-grid.css',
'/js/cart.js',
'/api/popular-products'
];
secondaryResources.forEach(url => {
this.preloader.generatePreloadLinks([{ url }]);
});
// 并行加载关键资源
await this.loader.loadCriticalResources();
}
// 产品页面优化
async optimizeProductPage(productId) {
// 根据网络状况调整图片加载
const networkInfo = this.getNetworkInfo();
const imageQuality = this.determineImageQuality(networkInfo);
// 生成响应式图片
const productImages = await this.fetchProductImages(productId);
const responsiveImages = productImages.map(img =>
this.imageOptimizer.generateResponsiveImages(img.url)
);
// 设置适当的缓存策略
this.cacheStrategy.setCacheHeaders(
{ set: (key, value) => console.log(`${key}: ${value}`) },
'semi-static'
);
return {
product: await this.fetchProduct(productId),
images: responsiveImages,
networkInfo,
imageQuality
};
}
determineImageQuality(networkInfo) {
if (!networkInfo) return 'high';
switch(networkInfo.effectiveType) {
case 'slow-2g':
return 'low';
case '2g':
return 'low';
case '3g':
return 'medium';
default:
return 'high';
}
}
getNetworkInfo() {
if ('connection' in navigator) {
return {
effectiveType: navigator.connection.effectiveType,
downlink: navigator.connection.downlink,
rtt: navigator.connection.rtt
};
}
return null;
}
async fetchProduct(productId) {
// 使用适当的缓存策略
const cacheKey = `product_${productId}`;
let product = await this.getFromCache(cacheKey);
if (!product) {
product = await fetch(`/api/products/${productId}`).then(r => r.json());
await this.setCache(cacheKey, product, 300); // 5分钟缓存
}
return product;
}
async fetchProductImages(productId) {
const response = await fetch(`/api/products/${productId}/images`);
return response.json();
}
async getFromCache(key) {
// 实现缓存获取逻辑
return localStorage.getItem(key);
}
async setCache(key, value, ttl) {
// 实现缓存设置逻辑
localStorage.setItem(key, JSON.stringify({
value,
expiry: Date.now() + (ttl * 1000)
}));
}
setupPerformanceMonitoring() {
// 监控资源加载性能
this.monitor.measureResourceTiming('/api/products');
this.monitor.measureResourceTiming('/css/main.css');
// 设置定期性能报告
setInterval(() => {
this.reportPerformanceMetrics();
}, 30000); // 每30秒报告一次
}
reportPerformanceMetrics() {
// 收集和报告性能指标
const metrics = {
timestamp: Date.now(),
navigation: performance.getEntriesByType('navigation')[0],
resources: performance.getEntriesByType('resource'),
paintTimings: performance.getEntriesByType('paint')
};
// 发送到性能监控服务
fetch('/api/performance', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(metrics)
}).catch(err => console.error('Performance reporting failed:', err));
}
}
// 初始化网络优化器
const networkOptimizer = new EcommerceNetworkOptimizer();
网络优化工具和库
性能分析工具
javascript
// 1. 网络性能分析工具
class NetworkAnalyzer {
static async analyzeConnection() {
const analysis = {
connection: navigator.connection ? {
effectiveType: navigator.connection.effectiveType,
downlink: navigator.connection.downlink,
rtt: navigator.connection.rtt,
saveData: navigator.connection.saveData
} : null,
performance: {
navigation: performance.getEntriesByType('navigation')[0],
timing: performance.timing
},
resources: performance.getEntriesByType('resource').map(entry => ({
name: entry.name,
duration: entry.duration,
size: entry.transferSize,
type: entry.initiatorType
}))
};
return analysis;
}
static generateNetworkReport() {
return `
网络连接分析报告
=================
连接类型: ${navigator.connection?.effectiveType || 'Unknown'}
下行带宽: ${navigator.connection?.downlink || 'Unknown'} Mbps
往返时间: ${navigator.connection?.rtt || 'Unknown'} ms
性能指标:
- DNS 查询: ${(performance.timing.domainLookupEnd - performance.timing.domainLookupStart)}ms
- TCP 连接: ${(performance.timing.connectEnd - performance.timing.connectStart)}ms
- 请求响应: ${(performance.timing.responseEnd - performance.timing.requestStart)}ms
- DOM 加载: ${(performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart)}ms
`;
}
}
// 2. 网络优化建议
class NetworkOptimizerAdvisor {
constructor() {
this.rules = [
{
condition: (metrics) => metrics.rtt > 300,
advice: '高延迟网络,考虑使用 CDN 或边缘计算',
severity: 'high'
},
{
condition: (metrics) => metrics.downlink < 0.5,
advice: '低带宽网络,优化资源大小和加载策略',
severity: 'high'
},
{
condition: (metrics) => metrics.effectiveType === 'slow-2g',
advice: '慢速 2G 网络,启用数据保护模式',
severity: 'critical'
},
{
condition: (metrics) => metrics.saveData,
advice: '启用了数据保护模式,优化资源压缩',
severity: 'medium'
}
];
}
getAdvice(networkInfo) {
const advice = [];
for (const rule of this.rules) {
if (rule.condition(networkInfo)) {
advice.push({
message: rule.advice,
severity: rule.severity
});
}
}
return advice;
}
}
网络优化检查清单
javascript
// 网络性能优化检查清单
const networkOptimizationChecklist = {
// 协议优化
protocol: [
'启用 HTTP/2',
'配置服务器推送',
'使用 SPDY (如果 HTTP/2 不可用)',
'启用 TLS 1.3',
'优化 TLS 握手',
'使用 OCSP 装订'
],
// 传输优化
transmission: [
'启用 Gzip/Brotli 压缩',
'优化图片格式和大小',
'使用 WebP/AVIF 格式',
'实现响应式图片',
'压缩 CSS 和 JavaScript',
'使用字体子集'
],
// 缓存优化
caching: [
'设置适当的缓存头',
'实现 ETag 支持',
'使用 CDN 分发',
'配置 Service Worker',
'实现缓存预热',
'设置缓存层级'
],
// 资源优化
resources: [
'优先加载关键资源',
'延迟加载非关键资源',
'实现资源预加载',
'使用代码分割',
'优化资源路径',
'减少 HTTP 请求数量'
],
// 监控优化
monitoring: [
'监控网络性能',
'测量首字节时间',
'跟踪资源加载时间',
'监控 CDN 性能',
'分析网络错误',
'设置性能预算'
],
// 安全优化
security: [
'使用 HTTPS',
'启用 HSTS',
'配置 CSP',
'使用安全的传输头',
'实施证书透明度',
'启用 HPKP (如果必要)'
]
};
// 网络性能评估类
class NetworkPerformanceEvaluator {
evaluateCurrentState() {
const evaluation = {
protocol: this.evaluateProtocol(),
compression: this.evaluateCompression(),
caching: this.evaluateCaching(),
resources: this.evaluateResources(),
monitoring: this.evaluateMonitoring()
};
const totalScore = Object.values(evaluation)
.flat()
.filter(item => item.implemented)
.length;
const maxScore = Object.values(networkOptimizationChecklist)
.flat()
.length;
return {
score: Math.round((totalScore / maxScore) * 100),
details: evaluation,
recommendations: this.getRecommendations(evaluation)
};
}
evaluateProtocol() {
// 实现协议评估逻辑
return [
{ item: 'HTTP/2', implemented: true, score: 20 },
{ item: 'HTTPS', implemented: true, score: 20 },
{ item: 'TLS 1.3', implemented: false, score: 0 }
];
}
evaluateCompression() {
// 实现压缩评估逻辑
return [
{ item: 'Gzip', implemented: true, score: 15 },
{ item: 'Brotli', implemented: false, score: 0 },
{ item: 'Image optimization', implemented: true, score: 15 }
];
}
evaluateCaching() {
// 实现缓存评估逻辑
return [
{ item: 'Browser caching', implemented: true, score: 10 },
{ item: 'CDN', implemented: true, score: 15 },
{ item: 'Service Worker', implemented: false, score: 0 }
];
}
evaluateResources() {
// 实现资源评估逻辑
return [
{ item: 'Resource prioritization', implemented: true, score: 10 },
{ item: 'Lazy loading', implemented: true, score: 10 },
{ item: 'Code splitting', implemented: false, score: 0 }
];
}
evaluateMonitoring() {
// 实现监控评估逻辑
return [
{ item: 'Performance monitoring', implemented: true, score: 10 },
{ item: 'Network metrics', implemented: true, score: 10 },
{ item: 'Error tracking', implemented: false, score: 0 }
];
}
getRecommendations(evaluation) {
const recommendations = [];
for (const [category, items] of Object.entries(evaluation)) {
items.forEach(item => {
if (!item.implemented) {
recommendations.push({
category,
item: item.item,
impact: item.score > 10 ? 'high' : 'medium'
});
}
});
}
return recommendations;
}
}
总结
网络性能优化需要从多个维度考虑:
- 协议优化 - 使用 HTTP/2、HTTP/3 等现代协议
- 传输优化 - 压缩、格式优化、内容分发
- 缓存优化 - 多层缓存策略
- 资源优化 - 加载策略、优先级管理
- 监控分析 - 持续监控和优化
通过系统性的网络优化,可以显著提升用户访问速度和体验。