Skip to content

Instantly share code, notes, and snippets.

@xnimorz
Created November 1, 2019 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnimorz/0b608077a2b190e16904a134765e6dc3 to your computer and use it in GitHub Desktop.
Save xnimorz/0b608077a2b190e16904a134765e6dc3 to your computer and use it in GitHub Desktop.
tti
window.globalVars.performance.pageWasActive = document.visibilityState === "visible";
document.addEventListener("visibilitychange", function(e) {
if (document.visibilityState !== "visible") {
window.globalVars.performance.pageWasActive = false;
}
});
function timeToInteractive() {
// Ожидаемое время TTI
const LONG_TASK_TIME = 2000;
// Максимально ожидаемое время TTI, если не произошло лонгтасок
const MAX_LONG_TASK_TIME = 30000;
const metrics = {
report: 'TTI',
};
if ('PerformanceObserver' in window && 'PerformanceLongTaskTiming' in window) {
let timeoutIdCheckTTI;
const longTask = [];
const observer = new window.PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
longTask.push(Math.round(entry.startTime + entry.duration));
}
});
observer.observe({ entryTypes: ['longtask'] });
const checkTTI = () => {
if (longTask.length === 0 && performance.now() > MAX_LONG_TASK_TIME) {
clearTimeout(timeoutIdCheckTTI);
}
const eventTime = longTask[longTask.length - 1];
if (eventTime && performance.now() - eventTime >= LONG_TASK_TIME) {
if (window.globalVars?.performance?.pageWasActive) {
StatsSender.sendMetrics({ ...metrics, tti: eventTime });
}
} else {
timeoutIdCheckTTI = setTimeout(checkTTI, LONG_TASK_TIME);
}
};
checkTTI();
}
}
export default timeToInteractive;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment