I need to check if a website is online and to get ping time.
I already have a rough ping time (close enough). But I still need to check if the site is online and make the function run five times, and get the lowest ping value (in order to get it more accurate).
My code so far:
<script>
function initPingTest(siteUrl){
pingTester();
function pingTester(){
document.getElementById('site').innerHTML = '<center>' + siteUrl + '</center>';
document.getElementById('pingT').innerHTML = '<center> testing.. </center>';
var startTime=new Date();
window.startTime=startTime.getTime();
var imgSrc=siteUrl+ '?cacheBuster='+Math.random();
var iFrame=document.getElementById('myPingTest');
iFrame.onload=pingTime;
iFrame.src=imgSrc;
function pingTime() {
var endTime=new Date();
var pingResult = (endTime.getTime()-window.startTime);
if(pingResult<hidden.hidden.value){
document.getElementById('pingT').innerHTML = '<center>' + pingResult + '</center>';
hidden.hidden.value=pingResult;
}else{document.getElementById('pingT').innerHTML = '<center>' + hidden.hidden.value + '</center>';}
}
}
}
</script>
<IFRAME style="display:none;" id=myPingTest></IFRAME>
<FORM NAME="hidden" STYLE="display:none"><INPUT TYPE="text" NAME="hidden" value="100000"></form>
<br>
<FORM method="get" NAME="ping" action="javascript:initPingTest(ping.url.value);"><font>Enter site adress(ie.www.yahoo.com)<br>http://</font>
<INPUT TYPE="text" NAME="url" size="18"><input type="submit" value="Ping"/></form>
<br>
<table cellspacing=5px>
<tr><th>
Url:
</th><th>
Ping Time (miliseconds)
</th></tr>
<tr><td>
<label id=site><center> - </center></label>
</td><td>
<label id=pingT><center> - </center></lable>
</td></tr>
</table>
</body></html>
While I don’t believe Javascript ‘really’ offers this kind of functionality, you could create an xmlhttprequest object, and perhaps compare the difference from the time it sends with the time it connects.
The following code shows a possible way to achieve this:
Edit: should alert if the server is down now
An iframe may be a viable solution as well though.