Html Picture Element Hack

I found myself needing to hide some images on mobile, but not on desktop AND without using the loading="lazy" attribute. The reasoning behind not using loading="lazy" is related to CLS and isn’t worth getting into. The workaround that I found was to use the <picture> element and then load a 1x1 pixel transparent image using a base64 encoded gif. TLDR; here’s the code:

<picture>
	<source media="(max-width: 991px)" srcset="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==">
	<source media="(min-width: 992px)" srcset="https://via.placeholder.com/130x130">
	<img src="https://via.placeholder.com/130x130" alt="Placeholder Image" />
</picture>

I first tried using a png instead of a gif, but found the gif saved about 12 extra bytes.

I came up with this solution myself, but after some further research I found someone else wrote an article about this as well. Here’s a link to their solution.

© 2014 - 2022 · Home ·