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
| class RUMMonitor {
constructor(apiEndpoint) {
this.apiEndpoint = apiEndpoint
this.metrics = {}
this.init()
}
init() {
// 监控页面加载
window.addEventListener('load', () => {
this.collectPageMetrics()
})
// 监控用户交互
this.monitorUserInteractions()
// 监控资源加载
this.monitorResourceLoading()
}
collectPageMetrics() {
const navigation = performance.getEntriesByType('navigation')[0]
this.metrics = {
dns: navigation.domainLookupEnd - navigation.domainLookupStart,
tcp: navigation.connectEnd - navigation.connectStart,
ssl: 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,
loadComplete: navigation.loadEventEnd - navigation.loadEventStart
}
this.sendMetrics()
}
monitorUserInteractions() {
['click', 'touchstart'].forEach(eventType => {
document.addEventListener(eventType, (event) => {
const startTime = performance.now()
requestAnimationFrame(() => {
const responseTime = performance.now() - startTime
if (responseTime > 100) { // 超过100ms的交互
this.recordSlowInteraction({
type: eventType,
target: event.target.tagName,
responseTime
})
}
})
})
})
}
monitorResourceLoading() {
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.duration > 1000) { // 超过1秒的资源
this.recordSlowResource({
name: entry.name,
duration: entry.duration,
size: entry.transferSize
})
}
}
})
observer.observe({ entryTypes: ['resource'] })
}
async sendMetrics() {
try {
await fetch(this.apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: window.location.href,
userAgent: navigator.userAgent,
timestamp: Date.now(),
metrics: this.metrics
})
})
} catch (error) {
console.error('Failed to send metrics:', error)
}
}
recordSlowInteraction(data) {
this.sendMetrics({
type: 'slow_interaction',
...data
})
}
recordSlowResource(data) {
this.sendMetrics({
type: 'slow_resource',
...data
})
}
}
// 初始化监控
const rumMonitor = new RUMMonitor('/api/analytics/performance')
|