Languages
[Edit]
EN

JavaScript - measure page loading times (connection, redirection, fetching, request, response, total)

4 points
Created by:
Gaia-Kirby
270

In this short article, we would like to focus on how to measure page loading times using JavaScript Performance API.

Presented below solution returns times similar to provided by Google Chrome DevTools.

Page loading times measured in Google Chrome DevTools and in JavaScript.
Page loading times measured in Google Chrome DevTools and in JavaScript.

Note: copy the below codes and put them on your site.

Practical example:

function checkPerformance() {
	if (performance.getEntries) {
		var entries = performance.getEntries();
		if (entries.length > 0) {
			return entries[0];
        }
	}
	return null;
}


function getTimes() {
	var performance = checkPerformance();
	if (performance) {
		return {
			connectingDuration: performance.connectEnd - performance.connectStart,
			redirectionDuration: performance.redirectEnd - performance.redirectStart,
			requestDuration: performance.responseStart - performance.requestStart,
			responseDuration: performance.responseEnd - performance.responseStart,
			fetchingDuration: performance.responseEnd - performance.requestStart,  // request time + TTFB + response time (downloading)
			totalDuration: performance.responseEnd - (performance.redirectStart || performance.connectStart)
		};
	}
	return null;
}

function onLoad() {
    var times = getTimes();
    if (times) {
        console.log(
            'connectingDuration: ' + times.connectingDuration + ' s\n' +
            'redirectionDuration: ' + times.redirectionDuration + ' s\n' +
            'requestDuration: ' + times.requestDuration + ' s\n' +
            'responseDuration: ' + times.responseDuration + ' s\n' +
            'fetchingDuration: ' + times.fetchingDuration + ' s\n' +
            'totalDuration: ' + times.totalDuration + ' s'
        );
    }
}

window.addEventListener('load', onLoad); // it is good to get times after page is loaded
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join