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

Cole picture Cole · Jun 9, 2011 · Viewed 27.3k times · Source

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.

Answer

Félix Saparelli picture Félix Saparelli · Jun 9, 2011

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.