Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  25] [ 2]  / answers: 1 / hits: 38439  / 14 Years ago, wed, september 29, 2010, 12:00:00

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

More From » css

 Answers
128

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.


[#95469] Sunday, September 26, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jimmieo

Total Points: 515
Total Questions: 102
Total Answers: 110

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;