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

荒凉一梦 提交于 2019-11-27 22:47:04

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:

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!