Peter Peter - 1 month ago 6
Javascript Question

How can I check if a background image is loaded?

I want to set a background image on the body tag, then run some code - like this:

$('body').css('background-image','http://picture.de/image.png').load(function() {
alert('Background image done loading');
// This doesn't work
});


How can I make sure the background image is fully loaded?

Answer

try this:

$('<img/>').attr('src', 'http://picture.de/image.png').load(function() {
   $(this).remove(); // prevent memory leaks as @benweet suggested
   $('body').css('background-image', 'url(http://picture.de/image.png)');
});

this will create new image in memory and use load event to detect when the src is loaded.

Comments