Languages
[Edit]
EN

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

4 points
Created by:
Gaia-Kirby
630

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 <script> code and put it on your site.

Practical example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script>
    
    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
    
  </script>
</head>
<body>
  <p>Web page content...</p>
</body>
</html>
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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