Don't load hidden images

Viewed 37742

I have a bunch of hidden images on my website. Their container DIVs have style="display: none". Depending on the user's actions, some images may be revealed via javascript. The problem is that all my images are loaded upon opening the page. I would like to put less strain on the server by only loading images that eventually become visible. I was wondering if there was a pure CSS way to do this. Here are two hacky/complicated ways I am currently doing it. As you can see, it's not clean code.

<div id="hiddenDiv">
   <img src="spacer.gif" />
</div>

.reveal .img {
 background-image: url(flower.png);
}

$('hiddenDiv').addClassName('reveal');

Here is method 2:

<img id="flower" fakeSrc="flower.png" />

function revealImage(id) {
 $('id').writeAttribute(
  'src',
  $('id').readAttribute('fakeSrc')
 );
}

revealImage('flower');
7 Answers

Weirdly, there's no answer about native lazy loading which is implemented in the majority of the browsers already.

you can do it by adding loading="lazy" attribute to your image.

Addy Osmani wrote a great article about it. You can read more about lazy loading here: https://addyosmani.com/blog/lazy-loading/

Related