fix: reduce LCP observation timeout to 100ms and enhance SPA navigation tracking with MutationObserver and history API integration
This commit is contained in:
@@ -208,12 +208,14 @@
|
|||||||
// * get a value. If the user navigates away before the delay, we leave LCP unset.
|
// * get a value. If the user navigates away before the delay, we leave LCP unset.
|
||||||
if (isSpaNav) {
|
if (isSpaNav) {
|
||||||
var thatId = data.id;
|
var thatId = data.id;
|
||||||
|
// * Run soon so we set lcpObserved before the user leaves; 500ms was too long
|
||||||
|
// * and we often sent metrics (next nav or visibilitychange+150ms) before it ran.
|
||||||
setTimeout(function() {
|
setTimeout(function() {
|
||||||
if (!lcpObserved && currentEventId === thatId) {
|
if (!lcpObserved && currentEventId === thatId) {
|
||||||
metrics.lcp = Math.round(performance.now() - routeChangeTime);
|
metrics.lcp = Math.round(performance.now() - routeChangeTime);
|
||||||
lcpObserved = true;
|
lcpObserved = true;
|
||||||
}
|
}
|
||||||
}, 500);
|
}, 100);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
@@ -529,15 +531,21 @@
|
|||||||
// * Fetch replay settings (async, doesn't block pageview)
|
// * Fetch replay settings (async, doesn't block pageview)
|
||||||
fetchReplaySettings();
|
fetchReplaySettings();
|
||||||
|
|
||||||
// * Track SPA navigation (history API)
|
// * Track SPA navigation: MutationObserver (DOM updates) and history.pushState/replaceState
|
||||||
|
// * (some SPAs change the URL without a DOM mutation we observe)
|
||||||
let lastUrl = location.href;
|
let lastUrl = location.href;
|
||||||
new MutationObserver(() => {
|
function onUrlChange() {
|
||||||
const url = location.href;
|
var url = location.href;
|
||||||
if (url !== lastUrl) {
|
if (url !== lastUrl) {
|
||||||
lastUrl = url;
|
lastUrl = url;
|
||||||
trackPageview();
|
trackPageview();
|
||||||
}
|
}
|
||||||
}).observe(document, { subtree: true, childList: true });
|
}
|
||||||
|
new MutationObserver(onUrlChange).observe(document, { subtree: true, childList: true });
|
||||||
|
var _push = history.pushState;
|
||||||
|
var _replace = history.replaceState;
|
||||||
|
history.pushState = function() { _push.apply(this, arguments); onUrlChange(); };
|
||||||
|
history.replaceState = function() { _replace.apply(this, arguments); onUrlChange(); };
|
||||||
|
|
||||||
// * Track popstate (browser back/forward)
|
// * Track popstate (browser back/forward)
|
||||||
window.addEventListener('popstate', trackPageview);
|
window.addEventListener('popstate', trackPageview);
|
||||||
|
|||||||
Reference in New Issue
Block a user