Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set background image of body after image is loaded?

For my site, I am using high-res pictures for the background of my body. If I simply put document.body.style.backgroundImage = "url('URL OF PICTURE')";, I can watch the image load vertically down the page. I want to only set the background image once the file has been loaded, and show my default grey background while it is loading. Any ideas?

like image 214
jas7457 Avatar asked Nov 17 '25 20:11

jas7457


1 Answers

You could use Image() to load it, listen for onload and then add it to the dom when it is loaded.

let img = new Image();

img.onload = function(){
    document.body.style.backgroundImage = "url('" + img.src + "')";
};

img.src = 'imageUrl.jpg';
like image 194
sanchez Avatar answered Nov 20 '25 10:11

sanchez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!