How to load an image asynchronously?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
In modern web development, asynchronous operations are crucial in maximizing performance and user engagement. Loading images asynchronously is a noteworthy method for enhancing web performance. This technique delays the loading of images until needed, optimizing resource usage, and reducing the immediate load on the user's device. Below, we explore various strategies and technologies used to load images asynchronously, complete with technical explanations and examples.
Why Load Images Asynchronously?
Loading images asynchronously offers several benefits:
- Improved Load Times: Fetching images only when needed speeds up the initial page load.
- Lower Bandwidth Usage: Only necessary images are loaded, conserving bandwidth.
- Enhanced User Experience: Reduced load times and smoother scrolling improve the overall user experience.
JavaScript Techniques for Asynchronous Image Loading
1. Lazy Loading
Lazy loading is a common technique where images are only loaded when they appear in the viewport. This approach can be implemented using JavaScript or native HTML features.
Native Lazy Loading with HTML
The native HTML way involves using the `loading` attribute in the ```<img>``` tag:
- `fetch(url)`: Initiates a network request to fetch the image.
- `response.blob()`: Converts the response to a binary object.
- `URL.createObjectURL(blob)`: Creates a local URL that can be set as the image's `src`.
- Use Optimal Image Formats: Choose formats like WebP or AVIF for better compression and smaller file sizes.
- Combine with CDN: Leveraging a Content Delivery Network (CDN) can enhance performance by reducing load times.
- Optimize for Accessibility: Always include appropriate attributes like `alt` for accessibility compliance.
- Lighthouse for measuring performance scores.
- Google Analytics to track user engagement.
Related reading
- How to load Image Masks Labels for Image Segmentation in Keras
- How to locate multiple objects in the same image?
- How to locate multiple objects in the same image?
- How to make a 2D Gaussian Filter in Tensorflow?
- How to load CSS Asynchronously
- How to log a method's execution time exactly in milliseconds?
- How to load video url's thumbnail image on tableview list Asynchronously
- How to make a clean Asynchronous loop?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.