Created
February 28, 2020 14:30
-
-
Save charlespwd/d79852b95ddeac4051aad82f27d5e93c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function trackOnClickFPS() { | |
window.dataLayer = window.dataLayer || []; | |
var start = performance.now(); | |
var end = start; | |
var diff = 0; | |
var page = ""; | |
var frameCount = 0; | |
var frcurr = start; | |
var frprev = start; | |
var frdiff = 0; | |
var frCount = 0; | |
var maxFramerate; | |
var rafId; | |
// Not all devices are 60hz | |
function findMaxFramerate() { | |
frcurr = performance.now(); | |
frdiff = frcurr - frprev; | |
if (frdiff < 30) { | |
// 33ms is 30fps, if you are below 30 you clearly are at max 60fps | |
maxFramerate = 60; | |
return; | |
} else if (frdiff < 60) { | |
// if you're between 30 and 60 fps, you might max at 30fps. We'll find | |
// 100 good frames and if you're close to 30fps for 10 frames then | |
// you're probably at max 30fps. | |
maxFramerate = 30; | |
frCount++; | |
} | |
frprev = frcurr; | |
if (frCount < 100) requestAnimationFrame(findMaxFramerate); | |
} | |
function debounce(onStart, onEnd, wait) { | |
var timeout; | |
return function() { | |
var args = arguments; | |
var later = function() { | |
timeout = null; | |
onEnd.apply(null, args); | |
}; | |
!timeout && onStart.apply(null, args); | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
}; | |
} | |
function onRaf() { | |
frameCount++; | |
requestAnimationFrame(onRaf); | |
} | |
var onInteraction = debounce( | |
function onStart(e) { | |
start = performance.now(); | |
selector = [ | |
e.target.id ? "#" + e.target.id : "", | |
e.target.className ? "." + e.target.className : "" | |
].join(""); | |
frameCount = 0; | |
rafId = requestAnimationFrame(onRaf); | |
}, | |
function onEnd() { | |
end = performance.now(); | |
diff = (end - start) / 1000; // seconds | |
cancelAnimationFrame(rafId); | |
window.dataLayer.push({ | |
eventName: "onclick framerate", | |
eventCategory: "rendering performance", | |
eventValue: ~~((frameCount / diff / maxFramerate) * 60), // value [0,60], 60 is maxFramerate, ~~ is fast floor. | |
eventLabel: selector | |
}); | |
}, | |
1000 | |
); | |
window.document.addEventListener("click", onInteraction); | |
requestAnimationFrame(findMaxFramerate); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment