The goal of this technique is to load large images only after the image is expanded, not on page load. Until the user toggles the image, only a thumbnail will be loaded.
To accomplish this reliably, we can use inlined CSS variables to load the image as a background.
Additionally, a technique I call "aspect ratio box" is used so that the image can be displayed in correct proportions regardless of what size the image scales into. Basically, percentages used on any padding (including top and bottom) are based on the parent element's width. So if you set padding-top to 50% and the parent's width is 200px, the padding-top will end up at exactly 100px. To get the padding-top value for a given image, use this calculation: (height / width * 100)
You can do this in various ways by using different toggleable element ↑ techniques, the examples below are nowhere near every option.
Caveats:
The image will not show up while it's loading, the entire image needs to finish loading before it shows up. Therefore if it loads slowly, it may look like it's broken.
The expanded image cannot be saved by right click or dragging it out of the window since it's a background-image. To make the image easier to download, you can wrap the whole thing inside a link to allow middle/right clicking to open/save it. Firefox seems to exhibit buggy behavior where left clicking sometimes opens the link instead of expanding the image though.
Research?
- Supposedly if an element is hidden with
display:none
, it's background image and none of it's child nodes' background images load. This behavior seems obscure and not well defined though so I wouldn't rely on it.
- Images that have
loading="lazy"
property should not load when they are hidden. However note that disabling javascript may disable lazy loading.