Event Timing APIでINPとクリックの応答時間を測る
Event Timing APIは、クリックやキー入力から次の描画までの時間をイベントごとに返すAPIです。入力遅延・処理時間・描画遅延に分けて遅い操作を見つけられ、INPの計測にも使います。Baseline 2025で使えます。
- Chrome76
- Edge79
- Firefox89
- Safari26.2
はじめに
Event Timing API(Performance Event Timing API)は、クリックやキー入力などのイベントが起きてから、ハンドラが動いて次に画面が描かれるまでの時間を、イベントごとに返すAPIです。Core Web VitalsのINP(Interaction to Next Paint)は、この時間から求めます。Safari 26.2が対応して、Baseline 2025に入りました。
ハンドラの処理にかかった時間は、performance.now()で前後を測れば分かります。ただ、ユーザーが感じる遅さには、ハンドラが動き出すまでの待ちと、ハンドラの後に画面が描かれるまでの時間も入ります。この2つまで含めて測るときに、Event Timing APIを使います。
基本的な使い方
PerformanceEventTimingは、PerformanceObserverで受け取ります。
<button type="button">クリックして計測</button>
<pre id="result">ボタンを押すと、ここに内訳が出ます</pre>// 50msかかるclickのハンドラ
document.querySelector('button').addEventListener('click', () => {
const start = performance.now();
while (performance.now() - start < 50) {}
});
const result = document.querySelector('#result');
const interactions = new Map();
// 1回の操作のentryから、内訳を出す
const show = (entries) => {
// durationが一番長いentryと、同じ描画で終わったentry
// durationは8ms単位に丸められるので、終わりが8ms以内なら同じ描画とみなす
const longest = entries.reduce((a, b) => (b.duration > a.duration ? b : a));
const paintTime = longest.startTime + longest.duration;
const sameFrame = entries.filter(
(entry) => Math.abs(entry.startTime + entry.duration - paintTime) <= 8,
);
const processingStart = Math.min(...sameFrame.map((entry) => entry.processingStart));
const processingEnd = Math.max(...sameFrame.map((entry) => entry.processingEnd));
// 入力遅延: 操作からハンドラ実行開始まで
const inputDelay = processingStart - longest.startTime;
// 処理時間: 同じ描画の前に動いたハンドラの実行時間
const processingTime = processingEnd - processingStart;
// 描画遅延: ハンドラ実行完了から次の描画まで(丸めで負になる分は0にする)
const presentationDelay = Math.max(0, paintTime - processingEnd);
result.textContent = [
`${sameFrame.map((entry) => entry.name).join(', ')}: ${longest.duration}ms`,
`入力遅延: ${inputDelay.toFixed(1)}ms`,
`処理時間: ${processingTime.toFixed(1)}ms`,
`描画遅延: ${presentationDelay.toFixed(1)}ms`,
].join('\n');
};
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
// interactionIdがないイベントはスキップ
if (!entry.interactionId) continue;
// 1回の操作で起きたイベント(pointerupとclickなど)のentryをまとめる
const entries = interactions.get(entry.interactionId) ?? [];
entries.push(entry);
interactions.set(entry.interactionId, entries);
show(entries);
}
});
observer.observe({
type: 'event',
buffered: true,
// 16ms以上のentryを受け取る。既定の104msでは、ふつうの操作がほとんど届かない
durationThreshold: 16,
});ボタンを押すと、クリックのdurationと内訳が出ます。clickのハンドラが50msかかるので、処理時間は約50msになります。
1回のクリックでは、pointerupとclickが同じ描画の前に処理され、どちらのdurationも同じ値になります。durationが一番長いentryを1つだけ選んで内訳を出すと、先に届くpointerupが選ばれ、clickのハンドラの時間が描画遅延に数えられます。押してから100ms後に離すクリックで50msかかるclickのハンドラを動かすと、どのブラウザでも、そのように選んだ内訳は処理時間が0ms、描画遅延が約48msになります。同じ描画で終わったentryの処理をまとめると、処理時間は約50msになります。
TypeScriptでは、getEntries()の型がPerformanceEntry[]なので、as PerformanceEventTiming[]で絞ります。PerformanceObserverInitの型にはdurationThresholdが無く、そのまま書くとTS2353になります。
対象のイベントとプロパティ
PerformanceEventTimingが届くイベントは、次のとおりです。
- クリック:
auxclick、click、contextmenu、dblclick - コンポジション:
compositionend、compositionstart、compositionupdate - ドラッグ:
dragend、dragenter、dragleave、dragover、dragstart、drop - 入力:
beforeinput、input - キーボード:
keydown、keypress、keyup - マウス:
mousedown、mouseenter、mouseleave、mouseout、mouseover、mouseup - ポインター:
pointerover、pointerenter、pointerdown、pointerup、pointercancel、pointerout、pointerleave、gotpointercapture、lostpointercapture - タッチ:
touchstart、touchend、touchcancel
PerformanceEventTimingのプロパティは、次のとおりです。
startTime:操作が起きた時刻duration:startTimeから次の描画までの時間name:イベントの種類entryType:type: 'event'で受け取るとevent、type: 'first-input'で受け取るとfirst-inputinteractionId:同じ操作で起きたイベントに共通のID。操作に結び付かないイベントでは0processingStart:ハンドラが動き出した時刻processingEnd:ハンドラが終わった時刻。ハンドラが無ければprocessingStartと同じcancelable:イベントのcancelableと同じ値target:イベントが起きた要素。DOMから外されるとnull
durationは8ms単位に丸められます。130msかかるハンドラのdurationが128msになることもあるので、durationからハンドラの時間を引くと、負になることがあります。
interactionIdは、1回のクリックで起きるpointerdownとpointerupとclickや、1回のキー入力で起きるkeydownとkeypressとkeyupで同じ値になります。どのブラウザでも、クリックのmousedownとmouseupは0です。
Shadow DOMの中の要素で起きたイベントでは、どのブラウザでもtargetはShadow DOMを持つホストの要素になります。
INP
INPは、ページを開いてから閉じるまでで一番遅かった操作の時間です。基本的な使い方で集めたinteractionsなら、一番長いdurationがINPになります(インタラクションが多いページでは、50回ごとに一番遅いものを1つ除きます)。ページを閉じる前に送るなら、visibilitychangeでhiddenになったときに求めます。
// ページが隠れるときに、一番遅いインタラクションのdurationを出す
document.addEventListener('visibilitychange', () => {
if (document.visibilityState !== 'hidden') return;
const durations = [...interactions.values()].flat().map((entry) => entry.duration);
console.log(`INP: ${Math.max(...durations)}ms`);
});基本的な使い方のコードはdurationThresholdを16msにしています。指定しないと、durationが104ms未満のインタラクションは届かず、INPが104ms未満のページでは値を求められません。
FIDの計測
type: 'first-input'を指定すると、最初の入力イベントだけを受け取れます。これで、2024年3月にCore Web VitalsでINPに置き換えられた、FID(First Input Delay)を測れます。
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const fid = entry.processingStart - entry.startTime;
console.log(`FID: ${fid}ms`);
}
});
observer.observe({ type: 'first-input', buffered: true });FIDは、最初の操作からハンドラが動き出すまでの時間なので、processingStartからstartTimeを引きます。
おわりに
Event Timing APIを使うと、クリックやキー入力から次の描画までの時間を、入力遅延と処理時間と描画遅延に分けて測れます。1回の操作のイベントをinteractionIdでまとめれば、内訳もINPも求められます。