Skip to content

Instantly share code, notes, and snippets.

@JeremyJaydan
Created March 14, 2024 02:50
Show Gist options
  • Save JeremyJaydan/65e3545f976f275935de81ad6305064b to your computer and use it in GitHub Desktop.
Save JeremyJaydan/65e3545f976f275935de81ad6305064b to your computer and use it in GitHub Desktop.
log INP core web vital
function onDocumentClick(){
const start = performance.now();
runAfterFramePaint(() => {
const end = performance.now();
console.log(`Time to paint: ${end - start}ms`);
});
}
function onDocumentKeyDown(event: KeyboardEvent){
const start = performance.now();
runAfterFramePaint(() => {
const end = performance.now();
console.log(`Time to paint: ${end - start}ms`);
});
}
document.addEventListener('click', onDocumentClick);
document.addEventListener('keydown', onDocumentKeyDown);
/**
* Runs `callback` shortly after the next browser Frame is produced.
* https://webperf.tips/tip/measuring-paint-time/
*/
function runAfterFramePaint(callback) {
// Queue a "before Render Steps" callback via requestAnimationFrame.
requestAnimationFrame(() => {
const messageChannel = new MessageChannel();
// Setup the callback to run in a Task
messageChannel.port1.onmessage = callback;
// Queue the Task on the Task Queue
messageChannel.port2.postMessage(undefined);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment