Using the Network Information API in JavaScript

The Network Information API provides web applications with access to data regarding a user’s current network status, including effective connection types, round-trip times, and bandwidth estimates. By reading these metrics via the navigator.connection object in JavaScript, developers can dynamically adapt web content—such as serving lower-resolution assets or delaying heavy background tasks—to match the client’s current connection speed and latency.

Accessing the Connection Object

The Network Information API is exposed through the navigator.connection interface. Because vendor prefixes were historically used and browser support varies, it is best practice to check for availability before querying metrics:

const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

if (connection) {
  console.log("Network Information API is supported.");
} else {
  console.log("Network Information API is not supported.");
}

Reading Connection Types and Speed Metrics

Once accessed, the connection object exposes several key properties that describe the network’s capabilities:

Example: Reading Metrics

if (connection) {
  console.log(`Effective Connection Type: ${connection.effectiveType}`);
  console.log(`Estimated Bandwidth: ${connection.downlink} Mbps`);
  console.log(`Round-Trip Time (RTT): ${connection.rtt} ms`);
  console.log(`Data Saver Active: ${connection.saveData}`);
}

Listening for Network Changes

Network conditions fluctuate frequently, especially on mobile devices. The API allows you to monitor these fluctuations in real time by attaching an event listener to the change event on the connection object:

function handleConnectionChange() {
  const { effectiveType, downlink, rtt } = connection;
  console.log(`Network updated: Type = ${effectiveType}, Speed = ${downlink} Mbps, RTT = ${rtt} ms`);

  if (effectiveType === 'slow-2g' || effectiveType === '2g') {
    // Switch to low-bandwidth mode (e.g., disable video autoplay, load low-res images)
  }
}

if (connection) {
  connection.addEventListener('change', handleConnectionChange);
}

Practical Implementation: Adaptive Loading

You can use these metrics to conditionally load resources. For example, dynamically selecting image quality based on connection quality:

function getOptimalImageURL(highResUrl, lowResUrl) {
  if (!connection) return highResUrl;

  if (connection.saveData || connection.effectiveType.includes('2g')) {
    return lowResUrl;
  }
  
  return highResUrl;
}