2 min read

Network Information API

The Network Information API provides information about the system's connection type (e.g., 'wifi', 'cellular', etc.) and capabilities (bandwidth, latency). This allows web applications to adapt their content based on the network quality.

1. Accessing Connection Info

The API is accessed via the navigator.connection object.

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

if (connection) {
  console.log("Effective Type: " + connection.effectiveType);
  console.log("Downlink Speed: " + connection.downlink + "Mb/s");
  console.log("Round Trip Time: " + connection.rtt + "ms");
  console.log("Save Data Mode: " + connection.saveData);
}

2. Properties

  • effectiveType: The effective connection type ('slow-2g', '2g', '3g', '4g'). This is determined by round-trip time and downlink values, not just the technology used.
  • downlink: The effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25kbps.
  • rtt: The estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds.
  • saveData: Returns true if the user has set a reduced data usage option on the user agent.
  • type: The type of connection ('bluetooth', 'cellular', 'ethernet', 'none', 'wifi', 'wimax', 'other', 'unknown'). Note: Support for this specific property is limited.

3. Listening for Changes

You can listen for the change event to detect when the network quality changes.

if (connection) {
  connection.addEventListener('change', () => {
    console.log("Connection changed!");
    console.log("New Effective Type: " + connection.effectiveType);
    console.log("New Downlink: " + connection.downlink);
  });
}

4. Use Cases (Adaptive Loading)

  • Images/Video: Load lower resolution media if effectiveType is '2g' or '3g', or if saveData is true.
  • Features: Disable heavy background sync or pre-fetching on slow connections.
  • Offline Mode: Detect if the user goes offline (though navigator.onLine is often used for simple online/offline checks).
if (connection && (connection.saveData || connection.effectiveType.includes('2g'))) {
  // Load low-res image
  img.src = 'low-res.jpg';
} else {
  // Load high-res image
  img.src = 'high-res.jpg';
}

programming/javascript/vanilla/javascript programming/javascript/vanilla/events programming/javascript/vanilla/performance-api