Created
November 6, 2023 05:45
-
-
Save PatrickJS/8e78754cbe1fb83d281efb1a765b933f to your computer and use it in GitHub Desktop.
navigator.connection.downlink or || I needed a quick way to determine if the user connection speed was fast enough to enable/disable some features in a site I’m working on, I made this little script that averages the time it takes to download a single (small) image a number of times, it's working pretty accurately in my tests, being able to clea…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var arrTimes = []; | |
| var i = 0; // start | |
| var timesToTest = 5; | |
| var tThreshold = 150; //ms | |
| var testImage = "http://www.google.com/images/phd/px.gif"; // small image in your server | |
| var dummyImage = new Image(); | |
| var isConnectedFast = false; | |
| testLatency(function(avg){ | |
| isConnectedFast = (avg <= tThreshold); | |
| /** output */ | |
| document.body.appendChild( | |
| document.createTextNode("Time: " + (avg.toFixed(2)) + "ms - isConnectedFast? " + isConnectedFast) | |
| ); | |
| }); | |
| /** test and average time took to download image from server, called recursively timesToTest times */ | |
| function testLatency(cb) { | |
| var tStart = new Date().getTime(); | |
| if (i<timesToTest-1) { | |
| dummyImage.src = testImage + '?t=' + tStart; | |
| dummyImage.onload = function() { | |
| var tEnd = new Date().getTime(); | |
| var tTimeTook = tEnd-tStart; | |
| arrTimes[i] = tTimeTook; | |
| testLatency(cb); | |
| i++; | |
| }; | |
| } else { | |
| /** calculate average of array items then callback */ | |
| var sum = arrTimes.reduce(function(a, b) { return a + b; }); | |
| var avg = sum / arrTimes.length; | |
| cb(avg); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment