Prevent Loading Hidden Images

Make sure that images hidden through 'display:none' are not downloaded by the browser.

Last Updated : May 29, 2020


TLDR : If all you care about is code for this to work, just go to this section and grab the code snippet.

Hiding an Image Doesn't Mean it Won't be Loaded

The most intuitive approach to hide an image is to set it's display property to none. The problem with this is that even if the image is not displayed, it does get downloaded.

<!--Even though not displayed, below image will be loaded by the browser -->
<img src="abc.jpg" 
    alt="Your Alt Text Here" title="Your Title Text Here" 
    style="display:none;" />

Hiding and Not Loading an Image

The best way to ensure that an image is not just hidden, but also not downloaded by the browser for a specific screen size is by using srcset attribute for ``:

<!--Below image will not be loaded or displayed when browser calculates screen width to be closer to 480px -->
<img src="myImage.jpg" 
    alt="Your Alt Text Here" title="Your Title Text Here" 
    srcset="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== 480w,
            myImage.jpg 900w"/>

Delay Loading Hidden Images

Often, an image is hidden initially and is displayed later - on page scross or on click of a button. The ideal way to handle loading of such images is to download them after initial page load. This helps improve page load times and keeps image instantly available for later interactions. Unfortunately, there's no non-JavaScript way to achieve this. Here's how it can be achieved through JavaScript:

!--Vanilla JS function to lazily load images after page is loaded-->
<script>
function lazyloadimages() {
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
  if(imgDefer[i].getAttribute('data-src'))
      imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
  }
}
window.onload = lazyloadimages;
</script>
<!--Use data-src for images -->
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" 
    alt="Your Alt Text Here" title="Your Title Text Here" 
    data-src="large.jpg" />

Given that the above approach uses JavaScript to lazy load images, we recommend you do so in an SEO friendly manner.



Punit Sethi

About the Author

Punit Sethi has been working with large e-Commerce & B2C websites on improving their site speed, scalability and frontend architecture. He tweets on these topics here.

Also Read