Search code examples
javascriptjquerycssloadbackground-image

How to verify background (css) image was loaded?


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?


Solution

  • 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;