If you're page has an Open Graph image, commonly used for social sharing, you can use it to set the background image at runtime with vanilla JavaScript like so:
<script>
const meta = document.querySelector('[property="og:image"]');
const body = document.querySelector("body");
body.style.background = `url(${meta.content})`;
</script>
The above uses document.querySelector
and Attribute Selectors to assign meta
the first Open Graph image it selects. A similar task is performed to get the body
. Finally, string interpolation is used to assign body
the background.style
the value of the path to the Open Graph image.
If you want the image to cover the entire viewport and stay fixed set background-size
like so:
body.style.background = `url(${meta.content}) center center no-repeat fixed`;
body.style.backgroundSize = 'cover';
Using this approach you can set a low-quality background image placeholder using CSS and swap with a high-fidelity image later using an image onload
event, thereby reducing perceived latency.