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

29,893

Solution 1

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.

Solution 2

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

http://jsfiddle.net/pWjBM/5/

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 :)

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.

http://jsfiddle.net/pWjBM/41/

HTML:

<div id="testdiv">
    <input type="text" id="txt" style="display:none;" />
</div>
<img src="http://www.nasa.gov/sites/default/files/images/712130main_8246931247_e60f3c09fb_o.jpg" id="dummy" style="display:none;" alt="" />

Javascript:

$(function() {
    $('#dummy').ready(function() { 
        alert('loaded');
        $('#testdiv').css('background-image', 'url(http://www.nasa.gov/sites/default/files/images/712130main_8246931247_e60f3c09fb_o.jpg)');
        $('#txt').show(1000);
    });
 });

CSS:

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

#txt{
    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.

Solution 3

do not set background in css, but load the image into an img tag created with javascript (or better, jquery). once loaded, it will fire the load event. when this event is fired, apply the style property to your div

Solution 4

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
    return;
}

It will work for background images and img tags.

Share:
29,893

Related videos on Youtube

Cole
Author by

Cole

I wish I had something to use Erlang for.

Updated on July 09, 2022

Comments

  • Cole
    Cole almost 2 years

    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.

  • mutex
    mutex almost 13 years
    I've been trying this approach to get around IE8s lack of a "DOMContentLoaded" event which appears to be why .ready() doesn't work with <= IE8... however it doesn't seem to work either. See the jquery documentation for .load() at api.jquery.com/load-event under "Caveats of the load event when used with images"
  • Luca Steeb
    Luca Steeb over 8 years
    And here's how to do it: stackoverflow.com/a/5058336/3062017
  • Félix Saparelli
    Félix Saparelli over 8 years
    In the future a more advanced, predictable, and possibly more efficient method for detecting whether assets referenced in CSS (images, fonts...) have loaded will be to use ServiceWorkers and postMessage: the Service Worker would load the asset, pass it to the page, and post a message to indicate the asset has loaded, in a way that is actionable from within JS, without relying on the browser's own caching to avoid an extra request.
  • Mustafa
    Mustafa over 6 years
    Do not set background in css? Listen. I use css background image so i can use the "cover" option. This is not possible with image tag unless you use a library which I dont think there is any as of writing this.
  • Senthil Kumaran C
    Senthil Kumaran C almost 3 years
    When Style applied , it will take image from cache. Nice Idea.