How can I tell when a CSS background image has loaded? Is an event fired? [duplicate]

I have a sidebar widget that has an image background.

Over this is a search input form. I don’t want the input to show before the image has loaded.

Is there a way to attach an load event handler to CSS background images like normal img elements/objects?

I know this could be done on a normal image, but I’d like to keep it as a CSS background because the image is part of a sprite. I am using jQuery, so solutions using jQuery or plain DOM JS are equally good.

You could load the same image using the DOM / a hidden image and bind to the load event on that. The browser’s caching should take care of not loading the image twice, and if the image is already loaded the event should fire immediately… not tested, tough.

In chrome, using .ready() of jQuery seems to work for me. Here’s my fiddle:

The image is just a random one I selected that is reasonably large – it actually takes a very long time to load in some of my tests, so may be worth replacing with something a bit smaller. But the end result is what you want I think: It takes a while to load, and once it’s loaded the alert and then textbox (#txt) displays. Seems to work in Firefox too; not sure about other browsers.

EDIT: Hah, it seems to work in Chrome, Firefox and Safari. Doesn’t work in IE8. So… it works in all real browsers 🙂

Read More:   How do I get the difference between two Dates in JavaScript?

EDIT2: After much fiddling, a combination of Allesandro and my own solution seems to work. I use .ready() on a hidden img to detect when the image is actually loaded, then load it into CSS background.


<div id="testdiv">
    <input type="text" id="txt" style="display:none;" />
<img src="" id="dummy" style="display:none;" alt="" />


$(function() {
    $('#dummy').ready(function() { 
        $('#testdiv').css('background-image', 'url(');


#testdiv {
    background:#aaaaaa none no-repeat right top;
    width: 400px;
    height: 400px;

    margin-left: 180px;
    margin-top: 140px;

NOTE: There is a comment below about this not working because you can change the url of the image and it still fires the loaded event. This is in fact working pretty much exactly as I’d expect given the current code – it doesn’t check if the url you’re pointing to for your “image” is valid and really an image, all it does is fires an event when the img is ready and change the background. The assumption in the code is that your url points to a valid image, and I think any further error checking is not really needed given the question.

You can try this, it’s pretty basic.

function onImageLoaded(url, callback) {
    const img = new Image();
    img.src = url;
    img.onloadend = callback;   //Image has loaded or failed

It will work for background images and img tags.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts