DEV Community

Cover image for Network Information API In JavaScript
Yiğit Kaan Korkmaz
Yiğit Kaan Korkmaz

Posted on

Network Information API In JavaScript

Hello everyone! I hope everyone has a fantastic day. Today i'm here to teach you the Network Information API.

It is still an experimental feature, which does not really work on some browsers very well for now, check out the browser support.

The Network Information API basically provides information about the system's connection, in terms of general connection type, like cellular, wifi, etc..

We can use this API to show users high quality of low quality content depending on their connection, for example a different image, or a different video.

You cannot really instantiate the NetworkInformation object, which contains all the info. So, how do we reach and use it? With the navigator.connection variable of course!

For example:

const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection; // We can use prefixes here

console.log(conn.effectiveType); // This should log the type of your connection
Enter fullscreen mode Exit fullscreen mode

We can also listen to events on the NetworkInformation object, events like connection changes, like the example below:

const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
let connType = conn.effectiveType;

function logConnectionChange() {
  console.log(`The connection type before: ${connType}`);
  console.log(`The connection type now: ${conn.effectiveType}`);

  connType = conn.effectiveType;
}

conn.addEventListener("change", logConnectionChange);
Enter fullscreen mode Exit fullscreen mode

We can also use it to preload videos or large amounts of information depending on the user's connection type, like the example below:

let preloadVideo = true;
const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

if (conn) {
  switch(conn.effectiveType) {
    case "cellular":
      preloadVideo = false;
    case "bluetooth":
      preloadVideo = false;
    case "slow-2g":
      preloadVideo = false;
    case "slow-3g":
      preloadVideo = false;
  }
}
Enter fullscreen mode Exit fullscreen mode

It is still an experimental feature but i really like it, because the ways we can use it are very flexible and immense. And this API will definetly help us use our resources in a better and more user friendly manner.

If you want to know more about the API, definetly check out the MDN Documentation of it.

Thank you for reading the article! If you think there are any mistakes, don't forget to comment it so i can check it out, and i most definetly do!

Top comments (0)