JavaScript 提供了一種估計使用者網路速度的方法,但需要注意的是,結果可能不是非常準確。
這個概念涉及載入已知檔案大小的圖片並測量它的時間需要載入。將所用時間除以圖像檔案大小(以位元組為單位),可以獲得互聯網速度的估計值。
可以在下面提供的連結中找到範例:
此修改後的測試案例包含解決潛在問題的修復程式:
// EXAMPLE ONLY. USE YOUR OWN IMAGE! var imageAddr = "https://upload.wikimedia.org/wikipedia/commons/3/3a/Bloemen_van_adderwortel_%28Persicaria_bistorta%2C_synoniem%2C_Polygonum_bistorta%29_06-06-2021._%28d.j.b%29.jpg"; var downloadSize = 7300000; // bytes function ShowProgressMessage(msg) { // Display progress messages on the console and a progress element on the page. if (console) { if (typeof msg == "string") { console.log(msg); } else { for (var i = 0; i < msg.length; i++) { console.log(msg[i]); } } } var oProgress = document.getElementById("progress"); if (oProgress) { oProgress.innerHTML = (typeof msg == "string") ? msg : msg.join("<br />"); } } function InitiateSpeedDetection() { ShowProgressMessage("Loading the image, please wait..."); window.setTimeout(MeasureConnectionSpeed, 1); }; if (window.addEventListener) { window.addEventListener('load', InitiateSpeedDetection, false); } else if (window.attachEvent) { window.attachEvent('onload', InitiateSpeedDetection); } function MeasureConnectionSpeed() { var startTime, endTime; var download = new Image(); download.onload = function () { endTime = (new Date()).getTime(); showResults(); } download.onerror = function (err, msg) { ShowProgressMessage("Invalid image, or error downloading"); } startTime = (new Date()).getTime(); var cacheBuster = "?nnn=" + startTime; download.src = imageAddr + cacheBuster; function showResults() { var duration = (endTime - startTime) / 1000; var bitsLoaded = downloadSize * 8; var speedBps = (bitsLoaded / duration).toFixed(2); var speedKbps = (speedBps / 1024).toFixed(2); var speedMbps = (speedKbps / 1024).toFixed(2); ShowProgressMessage([ "Your connection speed is:", speedBps + " bps", speedKbps + " kbps", speedMbps + " Mbps" ]); } }
<h1>
以上是如何使用 JavaScript 估算我的網路速度?的詳細內容。更多資訊請關注PHP中文網其他相關文章!