DEV Community

Cover image for Get network information using JavaScript and optimize your app
Mohsindev369
Mohsindev369

Posted on • Updated on

Get network information using JavaScript and optimize your app

Have you every wanted to optimize your web application behavior based on the user internet performance? Maybe loading content in different qualities?

Network Information API

This API is accessed through the navigator.connection property. Here are some of the properties.

  • effectiveType
  • downlink
  • errt
  • saveData

effectiveType
The effectiveType property returns the effective type of the current connection.

navigator.connection.effectiveType //'slow-2g','2g','3g','4g'
Enter fullscreen mode Exit fullscreen mode

downlink
The downlink property returns the effective bandwidth.

navigator.connection.downlink //Bandwidth in mbps
Enter fullscreen mode Exit fullscreen mode

rrt
rrt property returns the round-trip time.

navigator.connection.rrt //round-trip time (ms)
Enter fullscreen mode Exit fullscreen mode

saveData
The saveData property returns a Boolean, Weather the user's data-saver is on or off.

navigator.connection.saveData //true or false 
Enter fullscreen mode Exit fullscreen mode

Using it in a practice example

Less say we want to represent a high quality video, We first make sure that data-saver is not enabled. And if the internet speed meets their requirements, We load the video accordingly.

if(
!navigator.connection.saveData &&
navigator.connection.effectiveType === '4g' &&
navigator.connection.downlink>2
) 
{
 loadVideo("4k")
} else {
loadVideo("low-quality")
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading. This I my first blog so sorry if there is any errors.

Top comments (0)