Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptHow to detect network speed using JavaScript?

How to detect network speed using JavaScript?

To detect the network speed using javascript, we will use the following approach.

Approach: Open the web page for which you want to know the connection speed. The page should be the one for which you want to add the javascript code for detecting the speed. Assign or set up the address of the image which you want to use for speed test to the variable. The variables for storing the test’s start time, end time, and download size should be created. Set the “downloadSize” equivalent to the image file size(In bytes). The end of the download action is assigned to activate when the image downloading is completed. It calculates the speed of the download process, and converts it to “kbps” and “mbps”.

Below is example illustrate the above approach:
Example:




<!DOCTYPE html>
<html>
    <head>
        <title>
          To detect network speed using JavaScript
        </title>
    </head>
    <body>
        <script type="text/javascript">
            var userImageLink = 
            var time_start, end_time;
            
            // The size in bytes
            var downloadSize = 5616998;
            var downloadImgSrc = new Image();
  
            downloadImgSrc.onload = function () {
                end_time = new Date().getTime();
                displaySpeed();
            };
            time_start = new Date().getTime();
            downloadImgSrc.src = userImageLink;
            document.write("time start: " + time_start);
            document.write("<br>");
  
            function displaySpeed() {
                var timeDuration = (end_time - time_start) / 1000;
                var loadedBits = downloadSize * 8;
                
                /* Converts a number into string
                   using toFixed(2) rounding to 2 */
                var bps = (loadedBits / timeDuration).toFixed(2);
                var speedInKbps = (bps / 1024).toFixed(2);
                var speedInMbps = (speedInKbps / 1024).toFixed(2);
                alert("Your internet connection speed is: \n" 
                      + bps + " bps\n" + speedInKbps 
                      + " kbps\n" + speedInMbps + " Mbps\n");
            }
        </script>
    </body>
</html>


Output:

RELATED ARTICLES

Most Popular

Recent Comments