Can you lazy load CSS background images?
It isn't available out of the box, but it can be done using IntersectionObserver.
CSS syntax for a single image:
--background-image-lazy: prague-3010406_1920_thumbnail.jpeg;
background-image: var(--background-image-lazy);
CSS syntax for multiple images using image-set
:
--background-image-set-lazy: image-lazy-set(
url("ekg_1280.png") type("image/png"),
"ekg_1280.webp" type("image/webp")
);
background-image: var(--background-image-set-lazy);
Large block example.
- Open browser developer console.
- Go to the Network tab.
- Observe the network traffic. Once the element with specified background appears in the viewport then the background should load.
- Make sure to clear the browser cache when reloading the page because the image will be in the cache and if it's in the cache then the browser renders the background.
Large block example. This relates to image-set