import { BrowserPerformance } from "./BrowserPerformance"; import { Metrics } from "./Metrics"; import { requestCallback } from "../requestIdleCallback"; function addLoadListener(fn) { return window.addEventListener && window.addEventListener("load", fn); } export class PageLoad { private static _loaded = false; private static _successListeners = []; /** * Install a listener to record browser page load timing metrics. */ static capturePageLoadMetrics() { // No performance timing data will be available until the page load event // has actually fired. // Ensure that we're recording metrics after page load. addLoadListener(() => { Metrics.timing("browser.dom_content_loaded", BrowserPerformance.domContentLoadedEventStart()); // Even inside of the page load event, the `loadEnd` event has not // completed yet. // If we want to record `loadEventEnd`, we need to defer computation // until after the event is complete. requestCallback(() => { Metrics.timing("browser.load", BrowserPerformance.loadEventEnd()); }); }); } /** * Setup a page load event listener * * When the application emits the successful page load event, we record a * Metric indicating the page the user landed on and how much time has elapsed * since the current document was initialized. */ static listenForSuccess() { this.addSuccessListener((key: string): void => { Metrics.timing(key, BrowserPerformance.timeSinceTimeOrigin()); }); } /** * Register a listener that will be invoked when the first page is * successfully loaded. */ static addSuccessListener(fn) { this._successListeners.push(fn); } /** * Record a successful page load, once and only once. * * If the user lands on page A and we record a successful load, we do not * then want to record a second "page load" when they navigate to page B. */ static markSuccessfulLoad(key: string) { if (this._loaded) { return; } this._loaded = true; this._successListeners.forEach((fn) => { fn(key); }); } static reset() { this._loaded = false; this._successListeners = []; } }