This is an interesting question that is still relevant in 2022. It is easy to hide an image using media queries and display:none;
(as per the other answer):
@media(max-width: 600px) {
.post .sc_image img {
display: none;
}
}
However the image still loads in the background - which definitely isn't ideal for pagespeed and core web vitals.
You can use loading="lazy"
combined with the above solution to ensure the image doesn't load if it isn't displayed:
<img loading="lazy" src="cool-car.webp" class="sc_image" width="200" height="125" alt="This is a photo of my cool car" />
But what happens if this image happens to be near the top of the page on Desktop - "above the fold"? Adding lazy loading could cause a performance hit.
You could add the image to CSS as a background-image, but that has its own issues - namely that you can't (at the moment) support newer image file formats with a fallback yet using background-image: image-set()
.
I got stuck with this problem, and came up with this solution - using an old-school transparent 1x1 pixel as my fallback for smaller screens:
<picture class="sc_image">
<source srcset="pixel.png" media="(max-width: 600px)">
<source srcset="cool-car.webp" type="image/webp">
<source srcset="cool-car.png" type="image/png">
<img src="cool-car.png" width="200" height="125" alt="This is a photo of my cool car">
</picture>
I'm not sure if this is the best approach, but I think it is. For now.