1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
| // 实时性能监控系统
class RealTimePerformanceMonitor {
constructor() {
this.metrics = {
navigation: {},
resources: [],
vitals: {},
userInteractions: []
};
this.thresholds = {
LCP: 2500,
FID: 100,
CLS: 0.1,
TTFB: 800,
FCP: 1800
};
this.startMonitoring();
}
// 开始监控
startMonitoring() {
this.observeNavigation();
this.observeResources();
this.observeWebVitals();
this.observeUserInteractions();
this.startContinuousMonitoring();
}
// 观察页面导航
observeNavigation() {
window.addEventListener('load', () => {
const navigation = performance.getEntriesByType('navigation')[0];
this.metrics.navigation = {
dnsLookup: navigation.domainLookupEnd - navigation.domainLookupStart,
tcpConnect: navigation.connectEnd - navigation.connectStart,
sslHandshake: navigation.secureConnectionStart > 0
? navigation.connectEnd - navigation.secureConnectionStart
: 0,
ttfb: navigation.responseStart - navigation.requestStart,
download: navigation.responseEnd - navigation.responseStart,
domParse: navigation.domContentLoadedEventStart - navigation.responseEnd,
domReady: navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart,
pageLoad: navigation.loadEventEnd - navigation.loadEventStart
};
this.analyzeNavigationPerformance();
});
}
// 观察资源加载
observeResources() {
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
entries.forEach(entry => {
if (entry.entryType === 'resource') {
this.metrics.resources.push({
name: entry.name,
type: this.getResourceType(entry.name),
duration: entry.duration,
size: entry.transferSize,
cached: entry.transferSize === 0 && entry.decodedBodySize > 0,
startTime: entry.startTime
});
}
});
this.analyzeResourcePerformance();
});
observer.observe({ entryTypes: ['resource'] });
}
// 观察Web Vitals
observeWebVitals() {
// LCP
this.observeLCP();
// FID
this.observeFID();
// CLS
this.observeCLS();
// 其他指标
this.observeFCP();
this.observeTTFB();
}
// 观察LCP
observeLCP() {
new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
const lastEntry = entries[entries.length - 1];
this.metrics.vitals.LCP = {
value: lastEntry.renderTime || lastEntry.loadTime,
element: lastEntry.element?.tagName,
url: lastEntry.url
};
this.evaluateMetric('LCP', this.metrics.vitals.LCP.value);
}).observe({ entryTypes: ['largest-contentful-paint'] });
}
// 观察用户交互
observeUserInteractions() {
const interactionEvents = ['click', 'keydown', 'scroll', 'touchstart'];
interactionEvents.forEach(eventType => {
document.addEventListener(eventType, (event) => {
const interaction = {
type: eventType,
timestamp: Date.now(),
target: event.target.tagName,
coordinates: {
x: event.clientX,
y: event.clientY
}
};
this.metrics.userInteractions.push(interaction);
this.analyzeInteractionPattern(interaction);
});
});
}
// 开始持续监控
startContinuousMonitoring() {
setInterval(() => {
this.collectRealTimeMetrics();
this.detectPerformanceAnomalies();
this.updateDashboard();
}, 5000); // 每5秒更新一次
}
// 收集实时指标
collectRealTimeMetrics() {
const realTimeMetrics = {
timestamp: Date.now(),
memory: this.getMemoryUsage(),
network: this.getNetworkInfo(),
rendering: this.getRenderingPerformance(),
activeTime: this.getActiveTime()
};
this.metrics.realTime = realTimeMetrics;
}
// 获取内存使用情况
getMemoryUsage() {
if (performance.memory) {
return {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize,
limit: performance.memory.jsHeapSizeLimit,
percentage: (performance.memory.usedJSHeapSize / performance.memory.jsHeapSizeLimit) * 100
};
}
return null;
}
// 检测性能异常
detectPerformanceAnomalies() {
const anomalies = [];
// 检测内存泄漏
if (this.metrics.realTime?.memory?.percentage > 80) {
anomalies.push({
type: 'memory_leak',
severity: 'high',
message: 'Memory usage is above 80%'
});
}
// 检测长时间任务
const longTasks = this.getLongTasks();
if (longTasks.length > 0) {
anomalies.push({
type: 'long_tasks',
severity: 'medium',
message: `Detected ${longTasks.length} long tasks`,
details: longTasks
});
}
// 检测网络问题
if (this.metrics.realTime?.network?.effectiveType === 'slow-2g') {
anomalies.push({
type: 'slow_network',
severity: 'medium',
message: 'Network connection is very slow'
});
}
if (anomalies.length > 0) {
this.handleAnomalies(anomalies);
}
}
// 处理异常
handleAnomalies(anomalies) {
anomalies.forEach(anomaly => {
console.warn('Performance anomaly detected:', anomaly);
// 发送告警
this.sendAlert(anomaly);
// 尝试自动修复
this.attemptAutoFix(anomaly);
});
}
// 尝试自动修复
attemptAutoFix(anomaly) {
switch (anomaly.type) {
case 'memory_leak':
this.triggerGarbageCollection();
break;
case 'long_tasks':
this.optimizeTaskScheduling();
break;
case 'slow_network':
this.enableDataSavingMode();
break;
}
}
// 更新仪表板
updateDashboard() {
const dashboardData = {
vitals: this.metrics.vitals,
realTime: this.metrics.realTime,
resources: this.getResourceSummary(),
score: this.calculatePerformanceScore()
};
this.renderDashboard(dashboardData);
}
// 计算性能评分
calculatePerformanceScore() {
const weights = {
LCP: 0.3,
FID: 0.2,
CLS: 0.2,
FCP: 0.15,
TTFB: 0.15
};
let totalScore = 0;
let totalWeight = 0;
Object.entries(weights).forEach(([metric, weight]) => {
const value = this.metrics.vitals[metric]?.value || 0;
const threshold = this.thresholds[metric];
let score;
if (value <= threshold) {
score = 100;
} else if (value <= threshold * 2) {
score = 100 - ((value - threshold) / threshold) * 50;
} else {
score = 50 - ((value - threshold * 2) / threshold) * 25;
score = Math.max(0, score);
}
totalScore += score * weight;
totalWeight += weight;
});
return totalScore / totalWeight;
}
}
|