Skip to content

Instantly share code, notes, and snippets.

@alazycoder101
Created October 23, 2021 09:22
Show Gist options
  • Save alazycoder101/7c2dc9679fbff3e00372ebfca572d95a to your computer and use it in GitHub Desktop.
Save alazycoder101/7c2dc9679fbff3e00372ebfca572d95a to your computer and use it in GitHub Desktop.
speed test
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="grab bandwidth from Network Information.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Network Information</title>
<style>
body {
background-color: #ffffff;
box-sizing: border-box;
font-family: "Roboto", "Helvetica", "Arial", sans-serif;
}
@media screen and (min-width: 832px) {
body {
width: 800px;
margin: 0 auto;
}
}
h1 {
margin-bottom: -0.3em;
}
h2 {
margin-top: 2em;
}
h3 {
margin-bottom: -0.2em;
margin-top: 2em;
}
.output {
background-color: #f0f0f0;
border-radius: 0.75em;
display: block;
margin: 0.5em;
padding: 0.5em;
}
#status {
margin: .5em 0;
font-style: italic;
}
#log, #ping_log, #upload_log, #download_log {
margin: .5em 0;
white-space: pre-wrap;
}
#status:empty, #ping_log:empty, #upload_log:empty, #download_log:empty, #log:empty {
display: none;
}
</style>
<script>
// Add a global error event listener early on in the page load, to help ensure that browsers
// which don't support specific functionality still end up displaying a meaningful message.
window.addEventListener('error', function(error) {
if (Test && Test.setStatus) {
console.error(error);
Test.setStatus(error.message + ' (Your browser may not support this feature.)');
error.preventDefault();
}
});
var win = window;
function parseQueryVariables(query) {
var pair, hash = {}, i, vars = query.substring(1).split('&');
for (i = 0; i < vars.length; i++) {
pair = vars[i].split('=');
hash[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return hash;
}
var params = parseQueryVariables(win.location.search);
function getVariable(variable) {
if(params[variable]) {
return params[variable];
}
if (typeof win[variable] != 'undefined') {
return win[variable];
}
return '';
}
var times = parseInt(getVariable('times') || 5);
var host = 'st.site.my';
console.log('window.location.search=', win.location.search, 'times=', times);
</script>
</head>
<body>
<h1>Speed Test</h1>
<script>
var Test = {
log: function(line, id='log') {
//var line = Array.prototype.slice.call(arguments).map(function(argument) {
// return typeof argument === 'string' ? argument : JSON.stringify(argument);
//}).join(' ');
id = '#' + id;
document.querySelector(id).textContent += line + '\n';
},
clearLog: function(id='log') {
id = '#' + id;
document.querySelector(id).textContent = '';
},
setStatus: function(status) {
document.querySelector('#status').textContent = status;
}
};
</script>
<h3>Live Output</h3>
<div id="output" class="output">
<div id="status"></div>
<pre id="download_log"></pre>
<pre id="upload_log"></pre>
<pre id="ping_log"></pre>
<pre id="log"></pre>
</div>
<script>
var log = function(args, id) {
Test.log(args, id);
}
</script>
<script>
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
log ('Network connection');
log ('');
connection.addEventListener('change', logNetworkInfo);
function logNetworkInfo() {
// Network type that browser uses
log((new Date()).toLocaleString());
if (connection.type) {
log(' type: ' + connection.type);
}
// Effective bandwidth estimate
log(' downlink: ' + connection.downlink + 'Mb/s');
// Effective round-trip time estimate
log(' rtt: ' + connection.rtt + 'ms');
// Upper bound on the downlink speed of the first network hop
if (connection.downlinkMax) {
log(' downlinkMax: ' + connection.downlinkMax + 'Mb/s');
}
// Effective connection type determined using a combination of recently
// observed rtt and downlink values: ' +
log('effectiveType: ' + connection.effectiveType);
// True if the user has requested a reduced data usage mode from the user
// agent.
log(' saveData: ' + connection.saveData);
log('');
}
logNetworkInfo();
}
function ping(pong) {
var started = new Date().getTime();
var http = new XMLHttpRequest();
http.open("GET", location.protocol + "//"+host, /*async*/true);
http.ontimeout = function() {
log((new Date()).toLocaleString()+' Timeout', 'ping_log');
}
http.onerror = function() {
console.log((new Date()).toLocaleString()+' Error', 'ping_log');
}
http.onreadystatechange = function() {
if (http.readyState == 4) {
var ended = new Date().getTime();
var milliseconds = ended - started;
if (pong != null) {
pong(milliseconds);
}
}
};
try {
http.send(null);
} catch(exception) {
// this is expected
console.log('Exception:', exception);
log((new Date()).toLocaleString()+' Error', 'ping_log');
}
}
var images = [{url:"1M.jpg", size:1042592},
{url:"500K.jpg", size:555181},
{url:"2.5M.jpg", size:2504642}];
function downloadImage(imageAddr, downloadSize) {
imageAddr = imageAddr + "?n=" + Math.random();
var startTime, endTime;
var download = new Image();
download.onerror = function () {
log((new Date()).toLocaleString()+' ERROR', 'download_log');
}
download.onload = function () {
endTime = (new Date()).getTime();
showResults();
}
startTime = (new Date()).getTime();
download.src = imageAddr;
function showResults() {
var duration = Math.round( (endTime - startTime) / 10 + Number.EPSILON ) / 100
var bitsLoaded = downloadSize * 8;
var speedBps = Math.round(bitsLoaded / duration);
var speedKbps = (speedBps / 1024).toFixed(2);
var speedMbps = (speedKbps / 1024).toFixed(2);
log((new Date()).toLocaleString()+' '+speedMbps+" Mbps", 'download_log');
}
}
var pingTimes = 0;
function testPing() {
if (pingTimes < times) {
ping(function(m) { log((new Date()).toLocaleString()+" " + m + " ms", 'ping_log');});
} else {
clearInterval(pingInterval);
}
pingTimes++;
}
var imageIndex = 0;
function getRandomString( sizeInMb ) {
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_+`-=[]\{}|;':,./<>?", //random data prevents gzip effect
iterations = sizeInMb * 1024 * 1024, //get byte count
result = '';
for( var index = 0; index < iterations; index++ ) {
result += chars.charAt( Math.floor( Math.random() * chars.length ) );
};
return result;
};
var downloadTimes = 0;
function testDownload() {
if (downloadTimes < times) {
var image = images[downloadTimes % images.length];
downloadImage(location.protocol+"//"+host+'/rels/'+image['url'], image['size']);
} else {
clearInterval(interval);
}
downloadTimes++;
}
var speed, average;
function upload() {
var xhr = new XMLHttpRequest(),
url = location.protocol+'//'+host, //prevent url cache
data = getRandomString(1), //1 meg POST size handled by all servers
startTime,
speed = 0;
xhr.onreadystatechange = function ( event ) {
if(xhr.readyState == 4) {
speed = Math.round(1024/((new Date() - startTime)/1000));
average == 0 ? average = speed : average = Math.round((average + speed)/2);
log((new Date()).toLocaleString()+' '+speed+" kbs", 'upload_log');
};
};
xhr.ontimeout = function() {
log((new Date()).toLocaleString()+' Timeout', 'upload_log');
}
xhr.onerror = function() {
console.log('upload', xhr);
}
xhr.open( 'POST', url, true );
startTime = new Date();
xhr.send( data );
};
var uploadTimes = 0;
function testUpload() {
if (uploadTimes < times) {
upload();
} else {
clearInterval(uploadInterval);
}
uploadTimes++;
}
log('Download (every 30s)', 'download_log');
testDownload();
log('Ping (every 20s)', 'ping_log');
testPing();
testUpload();
log('Upload (every 25s)', 'upload_log');
var interval = setInterval(testDownload, 30000);
var uploadInterval = setInterval(testUpload, 25000);
var pingInterval = setInterval(testPing, 20000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment