Full Stack / 3 min read
Enhancing Image Performance with Network Information API
Introduction
Enhancing Image Performance with Network Information API

Introduction
Have you faced a problem that your website needs to perform better on poor network devices? And still, you want to provide all your users an enriching experience. One way to achieve this goal is using “Adaptive Images”. Adaptive images can significantly improve your application’s load time, first paint time, and other performance aspects.
Adaptive Images:
Depending on the type of connection and bandwidth the user has, modifying the image quality i.e., Images adapting the nature of bandwidth the user’s connection has.
How to achieve this:
Using JavaScript’s Network Information API, you can identify the type of connection and modify the image quality to provide viewers with slower connections and lower-quality images dynamically. To provide a better user experience, you will also require a fallback behaviour for browsers that do not implement the API.
Implementation of Adaptive Images
Here’s how you can implement adaptive images based on network quality using network API:
function getImageQuality() {
// Check if the Network Information API is supported
if ('connection' in navigator) {
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
// Adjust image quality based on connection type or effective bandwidth estimate
if (connection.effectiveType === '4g') {
return 'high'; // High-quality images for faster connections
} else if (connection.effectiveType === '3g' || connection.effectiveType === '2g') {
return 'medium'; // Medium quality for slower connections
} else if (connection.type === 'cellular' || connection.effectiveType === 'slow-2g') {
return 'low'; // Low quality for very slow connections
}
}
// Fallback: if Network Information API is not supported, serve medium quality by default
return 'medium';
}
// Dynamically load the appropriate image quality
function loadImage(imageElement, imageUrl) {
const quality = getImageQuality();
const qualityAdjustedUrl = imageUrl.replace('{quality}', quality); // Replace a placeholder with the selected quality
imageElement.src = qualityAdjustedUrl;
}
// Inserting the image once the DOM is fully loaded
document.addEventListener('DOMContentLoaded', function() {
// Geting image element by id
const imageElement = document.getElementById('adaptive-image');
// Check if the image element exists
if (imageElement) {
const baseImageUrl = 'https://example.com/images/picture-{quality}.jpg';
console.log('Image element found:', imageElement);
loadImage(imageElement, baseImageUrl);
} else {
console.error('Image element with ID "adaptive-image" not found');
}
});Explanation
- Once the DOM is loaded, find all image elements
loadImagefunction will get the image quality using Navigator API- Load the appropriate image from the server or CDN depending on the image quality.