Event Timing API All In One
Event Timing API All In One
const observer = new PerformanceObserver(function(list) {
const perfEntries = list.getEntries().forEach(entry => {
// Full duration
const inputDuration = entry.duration;
// Input delay (before processing event)
const inputDelay = entry.processingStart - entry.startTime;
// Synchronous event processing time (between start and end dispatch).
const inputSyncProcessingTime = entry.processingEnd - entry.processingStart;
});
});
// Register observer for event.
observer.observe({entryTypes: ["event"]});
https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEventTiming
https://w3c.github.io/event-timing/
https://w3c.github.io/event-timing/#sec-performance-event-timing
demo
// Keep track of whether (and when) the page was first hidden, see:
// https://github.com/w3c/page-visibility/issues/29
// NOTE: ideally this check would be performed in the document
// to avoid cases where the visibility state changes before this code runs.
let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity;
document.addEventListener('visibilitychange', (event) => {
firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp);
}, {once: true});
// Sends the passed data to an analytics endpoint. This code
// uses `/analytics`; you can replace it with your own URL.
function sendToAnalytics(data) {
const body = JSON.stringify(data);
// Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
(navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) ||
fetch('/analytics', {body, method: 'POST', keepalive: true});
}
// Use a try/catch instead of feature detecting `first-input`
// support, since some browsers throw when using the new `type` option.
// https://bugs.webkit.org/show_bug.cgi?id=209216
try {
function onFirstInputEntry(entry) {
// Only report FID if the page wasn't hidden prior to
// the entry being dispatched. This typically happens when a
// page is loaded in a background tab.
if (entry.startTime < firstHiddenTime) {
const fid = entry.processingStart - entry.startTime;
// Report the FID value to an analytics endpoint.
sendToAnalytics({fid});
}
}
// Create a PerformanceObserver that calls `onFirstInputEntry` for each entry.
const po = new PerformanceObserver((entryList) => {
entryList.getEntries().forEach(onFirstInputEntry);
});
// Observe entries of type `first-input`, including buffered entries, ?
// i.e. entries that occurred before calling `observe()` below.
po.observe({
type: 'first-input',
buffered: true,
});
} catch (e) {
// Do nothing if the browser doesn't support this API.
}
refs
https://web.dev/custom-metrics/#event-timing-api
?xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!