Deferring offscreen images means delaying the loading of images that are not immediately visible in the viewport when a user first lands on the page. By doing this, you can improve page load time and enhance user experience. Here's how you can defer offscreen images:
1. Use Native Lazy Loading (for Modern Browsers)
Most modern browsers support native lazy loading through the loading
attribute. Simply add the attribute with the value "lazy"
to your image tags:
<img src="image.jpg" alt="Description" loading="lazy">
This tells the browser to load the image only when it's about to be scrolled into view.
2. Implement a JavaScript Lazy Loading Library (for Broader Compatibility)
If you need to support browsers that don't have native lazy loading, you can use a JavaScript library like lozad.js
, lazysizes
, or others.
Here's an example using lozad.js
:
Include the library in your HTML:
<script src="path/to/lozad.min.js"></script>
Add a class (e.g.,
"lozad"
) to images you want to lazy load and use thedata-src
attribute instead ofsrc
:<img class="lozad" data-src="image.jpg" alt="Description">
Initialize the library in your script:
const observer = lozad('.lozad'); observer.observe();
3. Utilize CSS Background Images with Media Queries (if Applicable)
If you're using background images, you can use CSS media queries to load different images for different screen sizes or orientations, ensuring only the necessary image is loaded:
.background {
background-image: url('small-image.jpg');
}
@media (min-width: 800px) {
.background {
background-image: url('large-image.jpg');
}
}
4. Consider Adaptive Images for Different Devices
You can use the <picture>
and <source>
elements with media attributes to load different image sizes based on the device's capabilities:
<picture>
<source media="(max-width: 799px)" srcset="image-small.jpg">
<source media="(min-width: 800px)" srcset="image-large.jpg">
<img src="image.jpg" alt="Description">
</picture>
5. Monitor Performance
Use tools like Google Lighthouse to test and ensure that your images are being deferred appropriately.
Conclusion
Deferring offscreen images is an effective way to optimize the loading time of a webpage. Native lazy loading offers a simple solution for modern browsers, while JavaScript libraries provide broader compatibility. Combined with adaptive image techniques, these strategies can create a responsive and efficient loading experience.