function getPerformance(): Performance { return window.performance || ({ timing: {} } as Performance); } class LegacyTimingAPI { timing: PerformanceTiming; constructor(timing) { this.timing = timing; } get redirectEnd() { const { redirectEnd, navigationStart } = this.timing; return redirectEnd - navigationStart; } get responseEnd() { const { responseEnd, navigationStart } = this.timing; return responseEnd - navigationStart; } get domContentLoadedEventStart() { const { domContentLoadedEventStart, navigationStart } = this.timing; return domContentLoadedEventStart - navigationStart; } get loadEventEnd() { const { loadEventEnd, navigationStart } = this.timing; return loadEventEnd - navigationStart; } } /* * Get a handle to a timing object. * * If the browser supports the new timing API, return the new object. * If not, return a wrapper that simulates the new timing API. */ function getTiming() { const performance = getPerformance(); if (performance.getEntriesByType) { const entries: PerformanceNavigationTiming[] = performance.getEntriesByType( "navigation", ) as PerformanceNavigationTiming[]; if (entries.length > 0) { return entries[0]; } } return new LegacyTimingAPI(performance.timing); } export class BrowserPerformance { static redirectEnd(): number | null { const { redirectEnd } = getTiming(); if (redirectEnd) { return Math.floor(redirectEnd); } return null; } static responseEnd(): number | null { const { responseEnd } = getTiming(); if (responseEnd) { return Math.floor(responseEnd); } return null; } static domContentLoadedEventStart(): number | null { const { domContentLoadedEventStart } = getTiming(); if (domContentLoadedEventStart) { return Math.floor(domContentLoadedEventStart); } return null; } static loadEventEnd(): number | null { const { loadEventEnd } = getTiming(); if (loadEventEnd) { return Math.floor(loadEventEnd); } return null; } /** * A safe wrapper around the `performance.now()` browser API * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Performance/now} * * If the performance object does not exist, we return `null`. */ static now(): number | null { const performance = getPerformance(); if (performance.now) { return performance.now(); } return null; } /** * An alias for `now()` * * Returns the time diff since the "time origin" of the current document * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin} */ static timeSinceTimeOrigin = BrowserPerformance.now; }