It will be more painful than you think.
Your first problem is that Javascript does not have ping. Basically, Javascript is good at HTTP and several cousins.
The second problem is that you cannot just issue some ajax requests and result time (that would be too obvious). the same origin policy will not allow you to use ajax to communicate with servers other than the one the page was with. You will need to use JSONP or change the src of the image tag or something even more indirect.
Your third problem is that you do not want to do anything that will result in a lot of data being returned. You do not want data transfer times or advanced server processing to interfere with delay measurements.
Fourth, you cannot request URLs that can be cached. If the object was in the cache, you would get very low "latent" dimensions, but that would not make sense.
My solution was to use an image tag without the src attribute. When loading the document, install src on a valid server, but use an invalid port. Typically, the server rejects your connection faster than it generates the correct 404 error response. All you need to do is determine how long it takes to get the error event from the image.
From Filddle :
var start = new Date().getTime(); $('#junkOne').attr('src', 'http://fate.holmes-cj.com:8886/').error(function () { var end = new Date().getTime(); $('#timer').html("" + (end - start) + "ms"); });
Perhaps this method could be improved. Here are some ideas:
- Use an IP address instead of a DNS host name.
- Ping a few times, drop the highest and lowest grades, then compare the rest.
- If your webpage has a lot of heavy processing, try running tests when you think the user interface is the easiest.
source share