Adaptive serving based on network quality
Loading a website can be a very different experience depending on the network conditions. Everything is usually smooth when you are on a fast network, but when you're on the go with a limited data plan and spotty connection, or stuck with a laptop on slow coffee-shop Wi-Fi, it's a different story.
One way to deal with this is by adapting which assets you're serving to users based on the quality of their connection. This is now possible with the Network Information API which enables web applications to access information about the user's network.
- chrome 61, Supported 61
- firefox, Not supported ×
- edge 79, Supported 79
- safari, Not supported ×
There are many ways you can use this network information to improve the user experience:
- Switch between serving high-definition and low-definition content based on the user's network.
- Decide whether to preload resources.
- Defer uploads and downloads when users are on a slow connection.
- Enable offline mode if the network quality is not good enough to load the app and use the features.
- Warn users that doing something (for example, watching video) over cellular could cost them money.
- Use it in your analytics to gather data on your users' network quality.
Many applications are already doing something similar. For example, YouTube, Netflix and most other video (or video calling) services automatically adjust the resolution during streaming. When Gmail is loading, it provides users with a link to "load basic HTML (for slow connections)".
How it works #
navigator.connection object contains information about a client's connection. Its properties are explained in the table bellow.
|The bandwidth estimate in megabits per second.|
|The effective type of the connection, with possible values |
|An event handler that fires when connection information changes.|
|The estimated round-trip latency of the connection in milliseconds.|
|A boolean that defines whether the user has requested a reduced data usage mode.|
Here's what this looks like when you run it in the browser's console:
effectiveType values are also available via Client Hints and allow you to communicate the browser's connection type to servers.
onchange event listener enables you to dynamically adapt to changes in network quality. If you deferred uploads or downloads because of poor network conditions, you can rely on the event listener to restart the transfer when it detects better network conditions. You can also use it to notify users when the network quality changes. For example, if they lost their Wi-Fi signal and were dropped to a cellular network this can prevent accidental data transfers (and charges 💸).
onchange event listener as you would any other event listener:
The potential benefits of the Network Information API are big, especially for users on slow networks and applications that require a lot of bandwidth. Best of all, it can be used as a progressive enhancement technique.