Search code examples
javascriptphphtmlpage-load-time

How to get webpage load time


I need to get the load time for a webpage, but there's a catch. I've tried the nice little browser plugins like AppTelemetry for Firefox. But on a button click, my page redirects to a script on another page, runs the script, then redirects back to the original page and loads the page. I want to time that whole process from start to finish.

My understanding is that the client cannot write to a log file on the host system. Using JS to show an alert with system time doesn't work because it pauses until you click okay. Using a PHP script to record time to a server log file would work for timing execution of the redirect script, but that would exclude page load time. Is there any other way to measure the total load time including the redirects and scripts?


Solution

  • A very simple and elementary solution could be:

    1. on window load check for the loadTime variable in localstorage (no cookie)

    2. if it is not set it with current time and reload the page

    3. if finished to load compute the load time and remove the variable from localstorage.

    It's not the best but could give you a raw idea.

    The best way is to take a look to the console or write/use a plugin.

    window.onload=function(e) {
      var sample = localStorage.getItem("loadTime");
      if (sample == null) {
        localStorage.setItem("loadTime", new Date().getTime());
        window.location.reload(true);
      } else {
        var loadingTime = new Date().getTime() - sample;
        alert('Page loaded in: ' + loadingTime + 'milliseconds')
        localStorage.removeItem("loadTime")
      }
    }
    

    Another possibility is to avoid to reload the page simply setting the value of the starttime at the begginning of the page, directly in HTML, like:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <script type="text/javascript">
            var start = Date.now();
        </script>
        <meta charset="UTF-8">
        <title></title>
        <style>
        </style>
        <script>
            window.onload=function(e) {
                var loadingTime = new Date().getTime() - start;
                alert('Page loaded in: ' + loadingTime + 'milliseconds')
            }
        </script>
    </head>
    <body>
    
    </body>
    </html>