try this:
$('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() { $(this).remove(); // prevent memory leaks as @benweet suggested $('body').css('background-image', 'url(http://picture.de/image.png)'); });
this will create a new image in memory and use load event to detect when the src is loaded.
EDIT: in Vanilla JavaScript it can look like this:
var src = 'http://picture.de/image.png'; var image = new Image(); image.addEventListener('load', function() { body.style.backgroundImage = 'url(' + src + ')'; }); image.src = src;
it can be abstracted into handy function that return a promise:
function load(src) { return new Promise((resolve, reject) => { const image = new Image(); image.addEventListener('load', resolve); image.addEventListener('error', reject); image.src = src; }); } const image = 'http://placekitten.com/200/300'; load(image).then(() => { body.style.backgroundImage = `url(${image})`; });
Image()object which does haveonloadevent.url()