Explain Codes LogoExplain Codes Logo

How to detect internet speed in JavaScript?

javascript
performance
network-optimization
real-time-feedback
Nikita BarsukovbyNikita Barsukov·Feb 16, 2025
TLDR

Find a robust way to detect internet speed by measuring the time it takes to fetch a file. Here's how:

// Size of file in bytes (500KB) const fileSize = 500 * 1024; // Start the timer const start = performance.now(); // Fetch a file (e.g., "speedTest.png") fetch('speedTest.png?cache=' + Math.random()) // Cache bust, like the Kool-Aid Man 😉 .then(resp => resp.blob()) .then(() => { // Calculate speed (Mbps) const speed = fileSize * 8 / (1024 * 1024 * ((performance.now() - start) / 1000)); console.log(`Speed: ${speed.toFixed(2)} Mbps. Ridin' like the wind!`); });

Ride the waves of information with this known sized file, calculate the duration of the request, and compute the download speed in Mbps. For the best results, pick a file that can host a Speedy Gonzales race, like AWS S3; also, you might want to run more than one race just to make sure Speedy wasn't having a slow day.

Optimizing your performance: Handling test specifics

Add Network Information API to your speed-detecting toolkit

The Network Information API can give you an estimate of the speed without invoking extra downloads:

if ('connection' in navigator) { console.log(`Estimated speed: ${navigator.connection.downlink} Mbps. Our crystal ball at work!`); }

This API might not have the same fans in all browsers, and it’s more of an estimated guess than Sherlock Holmes' deduction.

Achieving consistent results with repeated testing

For a more rigorous test, do multiple file downloads and calculate an average speed:

async function testSpeed(iterations, file) { let speeds = []; for (let i = 0; i < iterations; i++) { // Ol' reliable while loop to the rescue const start = performance.now(); // Start the performance timer await fetch(file + "?no-cache=" + Math.random()).then(resp => resp.blob()); // Fetch while busting any pesky caches const end = performance.now(); // You shall not pass (any more time!) speeds.push(fileSize * 8 / (1024 * 1024 * (end - start) / 1000)); // Calculating speed in Mbps } // The Grand Reveal: Our average speed return (speeds.reduce((a, b) => a + b, 0) / speeds.length).toFixed(2); }

Finetune the precision: Using different file sizes

Pick the right tool, or rather, the right file size for the job: smaller files for quick checks and larger ones for a detailed analysis.

Flexibility counts: Adapting to varying device capabilities

Don't forget to tailor your speed test to the user’s device. A desktop might handle a big file, but for a mobile device, smaller is better. Use the properties of window object or media queries to achieve this customization.

Going beyond: Addressing real-world scenarios

Don’t let slow connections slow you down: Provide alternatives

Conditionally load media or other resources, based on the speed test results. For users with slower connections, lowering the resolution of images or disabling autoplay of videos can help.

Keep it light: Lessen the load for slow connections

Offer users an option to disable heavy content, giving a smoother experience with lower bandwidth.

Keep the users in the loop: Real-time feedback

Real-time speed display on the web page can keep users in the loop as to their current connection status.