reporting-lib
Version:
A comprehensive monitoring and reporting library for web applications
52 lines • 2.06 kB
JavaScript
class SPAPerformance {
constructor(callback) {
this.callback = callback;
this.routeStartMark = 'route-change-start';
this.routeEndMark = 'route-change-end';
}
markRouteStart() {
performance.mark(this.routeStartMark);
}
markRouteEnd() {
performance.mark(this.routeEndMark);
performance.measure('route-change-duration', this.routeStartMark, this.routeEndMark);
const measures = performance.getEntriesByName('route-change-duration');
if (measures.length > 0) {
const lastMeasure = measures[measures.length - 1];
this.callback('route-change-duration', lastMeasure.duration);
}
// 清理标记和测量,防止堆积
performance.clearMarks(this.routeStartMark);
performance.clearMarks(this.routeEndMark);
performance.clearMeasures('route-change-duration');
}
observeFirstContentfulPaint() {
// 这里用 web-vitals 的 onFCP 监听,或 PerformanceObserver
// 以示例简单用PerformanceObserver观察 FCP
const fcpObserver = new PerformanceObserver(list => {
for (const entry of list.getEntries()) {
if (entry.name === 'first-contentful-paint') {
this.callback('FCP', entry.startTime);
fcpObserver.disconnect();
break;
}
}
});
fcpObserver.observe({ type: 'paint', buffered: true });
}
watchKeyElement(selector) {
const el = document.querySelector(selector);
if (!el)
return;
const observer = new MutationObserver(() => {
// 这里简单假设有子节点或内容变就算渲染完成
if (el.childNodes.length > 0 || el.textContent.trim() !== '') {
this.markRouteEnd();
observer.disconnect();
}
});
observer.observe(el, { childList: true, subtree: true });
}
}
//# sourceMappingURL=routeChange.js.map
;