How to verify background (css) image was loaded?

thedp picture thedp · Dec 18, 2009 · Viewed 27.2k times · Source

I have the following CSS class that I'm applying on a <td> tag:

.bg {
   background-image: url('bg.jpg');
   display: none;
}

How can I tell with JavaScript/jQuery that the background image finished loading?

Answer

Jamie Dixon picture Jamie Dixon · Dec 18, 2009

The only way I know of to do this is to load the image using Javascript, and then set that image as the backgroud.

For example:

var bgImg = new Image();
bgImg.onload = function(){
   myDiv.style.backgroundImage = 'url(' + bgImg.src + ')';
};
bgImg.src = imageLocation;