Reputation: 41
Q. What technique is the most efficient in terms of image load times and performance...?
Scenario 1.
Is it to load a different size image by using a media query, as below:
/* Smartphone */
@media screen and (max-width: 320px) {
.img-page-1-img {
background: url('../images/img-page-1-img-117.jpg') no-repeat;
width: 117px;
height: 77px;
}
}
/* Desktop */
@media only screen and (min-width: 769px) {
.img-page-1-img {
background: url('../images/img-page-1-img-234.jpg') no-repeat;
width: 234px;
height: 154px;
}
}
OR...
Scenario 2.
Load one single large image and use CSS to "stretch" and resize by setting the max-width property..?
img {
max-width: 100%;
}
Thanks....
Upvotes: 3
Views: 6185
Reputation: 3606
Putting the different images in media queries won't work as some browsers will just preload all assets (even the ones that are no match for the current viewport).
See: http://www.nealgrosskopf.com/tech/thread.php?pid=73 for a nice overview.
I'd go for div's with data attributes that contain a reference to the image to load. Check window width (or use matchMedia) with javascript and create the image on the fly.
For images that are really important (content wise / need to be indexed) you could add a small version initially and replace it with a high resolution version if the window is wide enough (or media query is matched using matchmedia).
Upvotes: 1
Reputation: 174
for responsive design we need to add this to get original image for large screens
img {
max-width: 100%;
}
and inside the media queries add like this
@media screen and (max-width: 320px) {
width:117px;
}
and dont set height. you just control the image with parent by setting
overflow:hidden; height:117px;
**
and better to avoid background-images in responsive design, if you are using you should need 4 to 5 images for each set. Try to use img tag
**
Upvotes: 1
Reputation: 2211
Perhaps, an even more appropriate and/or responsive approach is to combine both. Use second img
as a fallback and use media queries with resolution
to specify the image:
img { ...low-res source }
@media (min-resolution: 2dppx) {
img { ...hi-res source }
}
An agent that understands high-res may throw away first request and fetch hi-res image only; in the worst case there would be two requests. Everyone else will only fetch low-res source.
resolution
is currently in W3 Candidate Recommendation
Upvotes: 1