Peter Peter - 5 months ago 34
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','').load(function() {
alert('Background image done loading');
// This doesn't work

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


try this:

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

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