如何在JavaScript 中估計網際網路速度
問題:如何建立一個JavaScript 頁面來估計使用者的網路速度互聯網速度並將其顯示在頁面上?
答案:
由於 Web 應用程式無法控制的因素,準確測量瀏覽器中的網路速度非常困難。但是,可以透過以下方式獲得近似估計:
範例:
以下 JavaScript程式碼示範了流程:
// Image address and file size (in bytes) var imageAddr = "https://large-image-url"; var downloadSize = 7300000; // Function to show progress messages function ShowProgressMessage(msg) { // Display messages in the console and a UI element } // Function to initiate speed detection function InitiateSpeedDetection() { ShowProgressMessage("Loading image..."); window.setTimeout(MeasureConnectionSpeed, 1); } if (window.addEventListener) { window.addEventListener('load', InitiateSpeedDetection, false); } else if (window.attachEvent) { window.attachEvent('onload', InitiateSpeedDetection); } // Function to measure connection speed function MeasureConnectionSpeed() { var startTime, endTime; var download = new Image(); // Event listeners for load and error download.onload = 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 to show speed results function showResults() { endTime = (new Date()).getTime(); 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" ]); } }
注意:
以上是如何使用 JavaScript 估算網路速度?的詳細內容。更多資訊請關注PHP中文網其他相關文章!