The following example shows how to use the API for all events:
const observer = new PerformanceObserver(function(list) {
const perfEntries = list.getEntries().forEach(entry => {
const inputDuration = entry.duration;
const inputDelay = entry.processingStart - entry.startTime;
const inputSyncProcessingTime = entry.processingEnd - entry.processingStart;
});
});
observer.observe({entryTypes: ["event"]});
We can also directly query the first input delay. The first input delay or FID, measures the time from when a user first interacts with a page (i.e. when they click a link or tap on a button) to the time when the browser is actually able to begin processing event handlers in response to that interaction.
let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity;
document.addEventListener('visibilitychange', (event) => {
firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp);
}, {once: true});
function sendToAnalytics(data) {
const body = JSON.stringify(data);
(navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) ||
fetch('/analytics', {body, method: 'POST', keepalive: true});
}
try {
function onFirstInputEntry(entry) {
if (entry.startTime < firstHiddenTime) {
const fid = entry.processingStart - entry.startTime;
sendToAnalytics({fid});
}
}
const po = new PerformanceObserver((entryList) => {
entryList.getEntries().forEach(onFirstInputEntry);
});
po.observe({
type: 'first-input',
buffered: true,
});
} catch (e) {
}