xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Event Timing API All In One

Event Timing API All In One

elementtiming

https://w3c.github.io/event-timing/

https://w3c.github.io/event-timing/#sec-performance-event-timing

const observer = new PerformanceObserver((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"]});

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 <head> 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()`.
  if(navigator.sendBeacon) {
    navigator.sendBeacon('/analytics', body)) 
  } else {
    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) => {
   // forEach(callback) / map(Number)
    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 (err) {
  // Do nothing if the browser doesn't support this API.
}


https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEventTiming

https://cdn.xgqfrms.xyz/Web-API/Event-Timing-API/index.html

FID

First Input Delay (FID) 指标测量从用户首次与页面交互到浏览器实际能够开始处理事件处理程序以响应该交互的时间。
但是,在某些情况下,测量事件处理时间本身以及直到可以渲染下一帧之前的时间也可能很有用。

这可以通过 Event Timing API(用于测量 FID)实现,因为它公开了事件生命周期中的许多时间戳,包括:

  1. startTime:浏览器接收到事件的时间。
  2. processingStart:浏览器能够开始针对该事件处理事件处理程序时的时间。
  3. processingEnd:浏览器完成执行事件处理程序针对该事件启动的所有同步代码时的时间。
  4. duration:浏览器收到事件直到它能够在完成执行从事件处理程序启动的所有同步代码后绘制下一帧时的时间(出于安全原因,四舍五入到 8 毫秒)。
// PerformanceObserver & entryList.getEntries

const FID = entry.processingStart - entry.startTime;
// Catch errors since some browsers throw when using the new `type` option.
// https://bugs.webkit.org/show_bug.cgi?id=209216
try {
  const po = new PerformanceObserver((entryList) => {
    const firstInput = entryList.getEntries()[0];

    // Measure First Input Delay (FID).
    const firstInputDelay = firstInput.processingStart - firstInput.startTime;

    // Measure the time it takes to run all event handlers
    // Note: this does not include work scheduled asynchronously using methods like `requestAnimationFrame()` or `setTimeout()`.
    const firstInputProcessingTime = firstInput.processingEnd - firstInput.processingStart;

    // Measure the entire duration of the event, from when input is received by the browser until the next frame can be painted after processing all event handlers.
    // Note: similar to above, this value does not include work scheduled asynchronously using `requestAnimationFrame()` or `setTimeout()`.
    // And for security reasons, this value is rounded to the nearest 8ms.
    const firstInputDuration = firstInput.duration;

    // Log these values the console.
    console.log({
      firstInputDelay,
      firstInputProcessingTime,
      firstInputDuration,
    });
  });

  po.observe({type: 'first-input', buffered: true});
} catch (err) {
  // Do nothing if the browser doesn't support this API.
}

https://web.dev/fid/

refs

https://web.dev/custom-metrics/#event-timing-api



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-04-29 17:06  xgqfrms  阅读(68)  评论(2编辑  收藏  举报