检测通用网速快慢
var getConnection = () => {
const nav = window.navigator;
if (!nav) return null;
return nav.connection || null;
};
var getNetworkState = function () {
const connection = getConnection();
if (!connection) {
return {
online: navigator.onLine,
};
}
return {
online: navigator.onLine,
type: connection.type,
effectiveType: connection.effectiveType,
downlink: connection.downlink,
downlinkMax: connection.downlinkMax,
rtt: connection.rtt,
saveData: connection.saveData,
};
};
var tipHandler = function () {
var state = getNetworkState();
console.table(state);
// var speed = navigator.connection.downlink * 1024 / 8; //单位为KB/sec
// console.log("网速为" + speed + "KB/s");
if(!state.online || state.downlink === 0) {
$(".network-tip").text('您当前设备离线,无法进行考试!')
} else if(state.downlink < 1) {
$(".network-tip").text('您当前网速较差,可能会影响考试!')
} else if (state.downlink < 5) {
$(".network-tip").text('您当前网速良好,可能会影响考试!')
} else {
$(".network-tip").text('您当前网速极好,可以正常考试!')
}
}
var connection = getConnection();
if (connection) {
connection.addEventListener("change", tipHandler);
}
tipHandler()
检测用户和特定域名之间的网络速度
function startDownload() {
var startTime = (new Date()).getTime();
var prevLoaded = 0; // 上次记录的已加载的数据量
var speeds = []; // 存储过去5秒的下载速度
var downloadTimeIntervalInMs = 5000; // 5秒
xhr = new XMLHttpRequest();
xhr.open('GET', '可以在公司cdn上放一个文件的链接', true);
xhr.responseType = 'arraybuffer';
// 设置请求超时时间为5秒
xhr.timeout = 5000;
xhr.onprogress = function(event) {
// 判断是否支持计算进度
if (event.lengthComputable) {
var currentTime = (new Date()).getTime();
var timeInterval = (currentTime - startTime) / 1000; // 总共用时(秒)
startTime = currentTime;
var loaded = event.loaded; // 已加载的数据量
var speed = (loaded - prevLoaded) / timeInterval / 1024; // kb/s
prevLoaded = loaded;
speeds.push(speed);
}
};
xhr.ontimeout = function() {
console.log('请求已超时,尝试中断请求...');
xhr.abort();
};
xhr.onload = function() {
if (xhr.status == 200) {
console.log('请求成功!');
} else {
console.log('请求失败:' + xhr.status);
}
};
console.log('开始下载...');
xhr.send(null);
setTimeout(function() {
var sum = speeds.reduce(function(a, b) {
return a + b;
}, 0);
var avg = sum / speeds.length;
console.log(`过去5秒的平均下载速度为: ${avg.toFixed(2)} KB/s`);
}, downloadTimeIntervalInMs);
}
startDownload()