Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Send CWV (Core Web Vitals) to Firebase Performance with the Target Element Names
<!-- 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
You can’t perform that action at this time.