JoJo JoJo - 4 years ago 143
Javascript Question

Don't load hidden images

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');

Answer Source

Here's a jQuery solution:

$(function () {
   $("img").not(":visible").each(function () {
       $(this).data("src", this.src);
       this.src = "";
   });

   var reveal = function (selector) {
       var img = $(selector);
       img[0].src = img.data("src");
   }
});

It's similar to your solution, except it doesn't use the fakeSrc attribute in the markup. It clears the src attribute to stop it from loading and stores it elsewhere. Once you are ready to show the image, you use the reveal function much like you do in your solution. I apologize if you do not use jQuery, but the process should be transferable to whichever framework (if any) that you use.

Note: This code specifically must be ran before the window has fired the load event but after the DOM has been loaded.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download