UNPKG

1.8 kBJavaScriptView Raw
1/**
2 * Exposes performance API if it exists in the current environment.
3 *
4 * @constant
5 * @private
6 * @type {Booelan}
7 */
8const performance = hasPerformanceApi() ? window.performance : undefined;
9
10/**
11 * Utility to check performance API.
12 *
13 * @return {Boolean}
14 * @private
15 */
16function hasPerformanceApi() {
17 return window &&
18 typeof window.performance !== 'undefined' &&
19 typeof window.performance.mark === 'function' &&
20 typeof window.performance.measure === 'function';
21}
22
23/**
24 * Utility to add a performance marker.
25 *
26 * @param {String} name
27 * @public
28 */
29export function mark(name) {
30 if (performance) {
31 performance.mark(name);
32 }
33}
34
35/**
36 * Utility to measure performance between the start and end markers.
37 *
38 * @param {String} comment
39 * @param {String} startMark
40 * @param {String} endMark
41 * @return {Void}
42 * @public
43 */
44export function measure(comment, startMark, endMark) {
45 // `performance.measure` may fail if the mark could not be found.
46 // reasons a specific mark could not be found include outside code invoking `performance.clearMarks()`
47 try {
48 performance.measure(comment, startMark, endMark);
49 } catch (e) {
50 // eslint-disable-next-line no-console
51 console.warn('performance.measure could not be executed because of ', e.message);
52 }
53}
54
55/**
56 * Utility to place end marker and measure performance.
57 *
58 * @param {String} comment
59 * @param {String} startMark
60 * @param {String} endMark
61 * @return {Void}
62 * @public
63 */
64export function markEndAndMeasure(comment, startMark, endMark) {
65 if (performance) {
66 mark(endMark);
67 measure(comment, startMark, endMark);
68 }
69}
70
71export default {
72 /**
73 * Utility to get window location object.
74 *
75 * @return {Object}
76 * @public
77 */
78 getLocation() {
79 return window && window.location;
80 }
81};