JavaScript Network Connection API

The Network Information API provides details about a device's current network connection. This information is accessed through the navigator.connection property, which returns a NetworkInformation object, which I'll discuss in this article.

Why Use It?

  • Optimizing Content Delivery: Developers can adjust the quality of images, videos, and other content based on the user's network speed. For example, low-resolution images can be served on slow connections to ensure faster load times.
  • Improving User Experience: Websites can dynamically adjust content delivery to respond to changes in network conditions, maintaining a smooth user experience.

Properties

The NetworkInformation object has several properties you might find useful:

  • effectiveType: Indicates the effective connection type ('slow-2g', '2g', '3g', or '4g').
  • downlink: Provides an estimate of the effective bandwidth in megabits per second (Mbps).
  • rtt: Returns the estimated round-trip time (RTT) in milliseconds.
  • saveData: A boolean that indicates if the user has enabled a reduced data usage option.
  • type: Describes the type of network connection (e.g., 'wifi', 'cellular').

Example time

Here's a simple example demonstrating how to use the Network Information API to log the connection type and respond to changes:

if ('connection' in navigator) {
    const connection = navigator.connection;

    console.log('Initial connection type:', connection.effectiveType);

    function updateConnectionStatus() {
        console.log('Connection type changed to:', connection.effectiveType);
    }

    connection.addEventListener('change', updateConnectionStatus);
} else {
    console.log('Network Information API is not supported in this browser.');
}

The script checks if the browser supports the Network Information API in this example. It then logs the initial connection type and sets up an event listener to log any changes in the connection type.

Notes

The Network Information API isn't widely supported, so always include a fallback. Check out the browser support here.

For more detailed information, refer to the MDN Web Docs on Network Information API.

JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.