Below is a JavaScript code snippet that tracks Time to First Paint(TFP), Time to First Contentful Paint(TFCP), Latency, and some other critical performance metrics. It then sends this data in a JSON format to an endpoint.
(function() {
document.addEventListener('DOMContentLoaded', function(){
var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {};
var performanceTiming = performance.timing;
var analyticsData = {}; // To store the metrics
// Time to First Paint (TFP)
if (performance.getEntriesByName) {
var firstPaint = performance.getEntriesByName('first-paint');
if (firstPaint && firstPaint.length > 0) {
analyticsData.TFP = firstPaint[0].startTime;
}
}
// Time to First Contentful Paint (TFCP)
if (performance.getEntriesByType) {
var contentfulPaint = performance.getEntriesByType('paint');
if (contentfulPaint && contentfulPaint.length > 0) {
for(var i = 0; i < contentfulPaint.length; i++){
if(contentfulPaint[i].name === 'first-contentful-paint'){
analyticsData.TFCP = contentfulPaint[i].startTime;
break;
}
}
}
}
// Latency
if (performanceTiming.responseEnd && performanceTiming.fetchStart) {
analyticsData.latency = performanceTiming.responseEnd - performanceTiming.fetchStart;
}
// Additional metrics - Page Load Time and Request Response Time
if (performanceTiming.loadEventEnd && performanceTiming.navigationStart) {
analyticsData.pageLoadTime = performanceTiming.loadEventEnd - performanceTiming.navigationStart;
}
if (performanceTiming.responseEnd && performanceTiming.requestStart) {
analyticsData.requestResponseTime = performanceTiming.responseEnd - performanceTiming.requestStart;
}
// Send data to the endpoint
var xhr = new XMLHttpRequest();
xhr.open("POST", 'https://acme.com/analytics', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200) return;
// In case of successful response, you may want to do something here.
};
xhr.send(JSON.stringify(analyticsData));
});
})();
This script captures Time to First Paint, Time to First Contentful Paint, Latency, Page Load Time, and Request Response Time. It needs to be run once the DOM has finished loading. It calculates these metrics using the performance APIs provided by modern browsers.
The metrics are then POSTed via an XMLHttpRequest to https://acme.com/analytics
endpoint. Got to make sure to handle cases where the performance API or specific properties are not available in the user's browser so that no errors should occur on such browsers.