Created
December 4, 2020 10:39
-
-
Save herablog/f04f473b9d9a8f63848f63ce0aec3eff to your computer and use it in GitHub Desktop.
Send CWV (Core Web Vitals) to Firebase Performance with the Target Element Names
This file contains hidden or 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
<!-- Firebase Performance SDK should be loaded before this script --> | |
<script type="module"> | |
/** | |
* Combine element with its ID and class names | |
* @pamam {HTMLElement} element | |
* @return {string} element name - e.g. div#id.classname | |
*/ | |
function combineElementWithIdAndClass(element) { | |
const idName = element.id ? `#${element.id}` : ''; | |
const className = element.className | |
? `.${element.className.split(' ').join('.')}` | |
: ''; | |
return `${element.tagName.toLowerCase()}${idName}${className}`; | |
} | |
/** | |
* Extract element names from list of elements | |
* @param {HTMLElement[]|HTMLElement} sources | |
* @return {string} element name - e.g. div#id.classname,img#hero | |
*/ | |
function extractElementNames(sources) { | |
if (Array.isArray(sources)) { | |
return sources.map((source) => | |
combineElementWithIdAndClass(source.node)).filter(Boolean).join(', '); | |
} | |
return combineElementWithIdAndClass(sources); | |
} | |
/** | |
* CWV metric. | |
* @external Metric | |
* @see {@link https://github.com/GoogleChrome/web-vitals#metric} | |
*/ | |
/** | |
* Send CWV to Firebase | |
* @param {Metric} | |
* @return {void} | |
*/ | |
function sendToFirebase({ name, delta, entries }) { | |
const metricNameMap = { | |
CLS: 'Cumulative Layout Shift', | |
LCP: 'Largest Contentful Paint', | |
FID: 'First Input Delay', | |
TTFB: 'Time To First Byte', | |
}; | |
const startTime = Date.now(); | |
const value = Math.round(name === 'CLS' ? delta * 1000 : delta); | |
entries.forEach(({ element, target, sources }) => { | |
const elements = element || target || sources; // LCP, FID, CLS | |
const elementName = elements ? extractElementNames(elements) : ''; | |
const attributes = elementName ? { element: elementName } : {}; | |
firebase.performance().trace(metricNameMap[name]).record( | |
startTime, | |
value, | |
attributes | |
); | |
}); | |
} | |
import('https://unpkg.com/web-vitals?module') | |
.then(({ getCLS, getFID, getLCP, getTTFB }) => { | |
getCLS(sendToFirebase); | |
getFID(sendToFirebase); | |
getLCP(sendToFirebase); | |
getTTFB(sendToFirebase); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment