views:

327

answers:

2

How to calculate approximately the connection speed of a website using JavaScript?

I want to create a javascript widget like, which will calculate the speed opening the current opened page.

I am asking if this can be done using just javascript and what will be the idea.

Update

Note that the page size is always Unknown.

A: 

Sure.

<script>
    startTime = Date.now();
    window.onload = function(){
        endTime = Date.now();
        //Time in ms between opening page, and loading all the date
        alert(endTime - startTime)
    };
</script>

Now to approximate speed. Statically you know let's say page is 200kb.

var kbps = 200 / (endTime - startTime * 1000);
Dmitri Farkov
and what if i don't know whats the page size in kb, can i get using js as well?
Amr ElGarhy
Javascript has no way of checking file-sizes of pages unfortunately, so I would have to say no.
Dmitri Farkov
This will not get you the connection speed. That gives you the load time the page takes to render.
epascarello
so how to get it? there is a smarter way?
Amr ElGarhy
The last line, calculates the average speed with which the page has loaded.
Dmitri Farkov
+5  A: 

Here's an example using AJAX with .Net backend, though it could be anything.

Here's a simpler example using an image.

The key is to have a page/object of a known size and capture the start and end times as the browser retrieves it. Then simply divide the size by some [unit of time] to get [size] per [unit of time]. Then use math to translate this into whatever you want.

Ryan Emerle
This is the correct answer.
Ciaran Archer