Last active
March 12, 2021 07:31
-
-
Save matthiasott/185dedbe921be5e359d70dc2590062d1 to your computer and use it in GitHub Desktop.
Check the current connection speed with the Resource Timing API
This file contains 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
let fastConnection = false; | |
/** | |
* Checks the current connection speed by calculating the time it takes to download a resource | |
* Uses the Resource Timing API: https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API | |
*/ | |
const checkConnectionSpeed = function(resource) { | |
// Check performance support | |
if (window.performance === undefined) { | |
console.log("! window.performance NOT supported"); | |
return; | |
} | |
// Get the performance entry for the poster image for the speed test | |
let payload = window.performance.getEntriesByName(resource)[0]; | |
// Return if there is no performance record for the resource | |
if (payload === undefined) { | |
console.log("! NO payload, quitting…"); | |
return; | |
} | |
// Download time: difference between response start and end times | |
let downloadTime = (payload.responseStart > 0) ? (payload.responseEnd - payload.responseStart) : "0"; | |
// Benchmark: If 100kb take 2000ms to download, we're approx. at the slowest DSL speed | |
let allowedTime = payload.transferSize / 100000 * 2000; | |
// Check if faster or slower than allowed (could be a switch, too) | |
if (downloadTime >= allowedTime) { | |
console.log("This is a slow connection. No videos for you today…"); | |
fastConnection = false; | |
} else if(downloadTime < allowedTime){ | |
console.log("Fast connection! Load the video!"); | |
fastConnection = true; | |
} | |
} | |
checkConnectionSpeed('https://example.org/resource.jpg'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment