Skip to content

Quick SEO Tips

HTML: Load Image Only On Desktop or Mobile

Category: Speed Optimization Published: Updated:

Problem: you want to have loading="eager" on an image located above the fold. However, that image should only be shown on mobile or desktop, giving it display: none; is ignored as the eager loading takes priority over it. The image gets downloaded on both desktop and image, even when one of the sizes does not use the image.

Solution: add an empty source image for the screen size that should not have an image. Here's how:

1<picture>
2 <source media="(max-width: 600px)" srcset="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" >
3 <img src="/example-image.png" height="560" width="255" aria-hidden="true" alt="" >
4</picture>

The code above loads the PNG image for all screen sizes over 600px, and for screen sizes less than 600px, a transparent 1x1px image gets loaded. That gif code is the smallest possible image that does not result in a failed image load, if you were to leave the srcset completely empty, browsers would either ignore the source and switch to the PNG image or they would show the broken image symbol.

If you wanted to show the image only on mobile, you would switch the max-width: 600px to min-width: 600px instead.

I added empty alt attribute and the aria-hidden to the example as I always only use them for decorative images. Reason for that is that if the image was important, you probably would want to show it on both desktop and mobile, if it is only shown on one of the, it probably is just decorative. If you know what you're doing, feel free to remove the aria-hidden and add an alt attribute. I have tested how Google reacts to that, and found out that Google never shows the hidden 1x1px image on Google Images, and only shows the actual existing file.

This is such a neat way to achieve this with pure HTML! No JS and no CSS, also supports having WebP with the JPG / PNG. If you are using loading="lazy" on the image, then you should not need this and can instead give inline styling display: none; on the image and then conditionally overwrite that style on your CSS file using a media query.