Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

css - Placeholder background/image while waiting for full image to load?

I have a few images on my page. I'm finding that the page starts to render before the images have been loading (which is good), but that the visual effect is not great. Initially the user sees this:

 --------hr--------
 text

Then a few milliseconds later the page jumps to show this:

--------hr--------
[           ]
[   image   ]
[           ]
text

Is there a simple way that I can show a grey background image of exactly the width and height that the image will occupy, until the image itself loads?

The complicating factor is that I don't know the height and width of the images in advance: they are responsive, and just set to width: 100% of the containing div. This is the HTML/CSS:

<div class="thumbnail">
<img src="myimage.jpeg" />
<div class="caption">caption</div>
</div>
img { width: 100% } 

Here's a JSFiddle to illustrate the basic problem: http://jsfiddle.net/X8rTB/3/

I've looked into things like LazyLoad, but I can't help feeling there must be a simpler, non-JS answer. Or is the fact that I don't know the height of the image in advance an insurmountable problem? I do know the aspect ratio of the images.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of referencing the image directly, stick it within a DIV, like the following:

<div class="placeholder">
    <div class="myimage" style="background-image: url({somedynamicimageurl})"><img /></div>
</div>

Then in your CSS:

.placeholder {
    width: 300;
    height: 300;
    background-repeat: no-repeat;
    background-size: contain;
    background-image: url('my_placeholder.png');
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...