如何显示加载图像,而实际图像下载

有时图像需要一些时间才能在浏览器中呈现。我想显示一个繁忙的图像,而实际的图像是下载,当图像下载,繁忙的图像是删除,实际的图像应该显示。如何使用 JQuery 或任何 javascript 实现这一点?

141423 次浏览

You can do something like this:

// show loading image
$('#loader_img').show();


// main image loaded ?
$('#main_img').on('load', function(){
// hide/remove the loading image
$('#loader_img').hide();
});

You assign load event to the image which fires when image has finished loading. Before that, you can show your loader image.

Just add a background image to all images using css:

img {
background: url('loading.gif') no-repeat;
}

I use a similar technique to what @Sarfraz posted, except instead of hiding elements, I just manipulate the class of the image that I'm loading.

<style type="text/css">
.loading { background-image: url(loading.gif); }
.loaderror { background-image: url(loaderror.gif); }
</style>
...
<img id="image" class="loading" />
...
<script type="text/javascript">
var img = new Image();
img.onload = function() {
i = document.getElementById('image');
i.removeAttribute('class');
i.src = img.src;
};
img.onerror = function() {
document.getElementById('image').setAttribute('class', 'loaderror');
};
img.src = 'http://path/to/image.png';
</script>

In my case, sometimes images don't load, so I handle the onerror event to change the image class so it displays an error background image (rather than the browser's broken image icon).

Use a javascript constructor with a callback that fires when the image has finished loading in the background. Just used it and works great for me cross-browser. Here's the thread with the answer.

Instead of just doing this quoted method from https://stackoverflow.com/a/4635440/3787376,

You can do something like this:

// show loading image
$('#loader_img').show();


// main image loaded ?
$('#main_img').on('load', function(){
// hide/remove the loading image
$('#loader_img').hide();
});

You assign load event to the image which fires when image has finished loading. Before that, you can show your loader image.

you can use a different jQuery function to make the loading image fade away, then be hidden:

// Show the loading image.
$('#loader_img').show();


// When main image loads:
$('#main_img').on('load', function(){
// Fade out and hide the loading image.
$('#loader_img').fadeOut(100); // Time in milliseconds.
});

"Once the opacity reaches 0, the display style property is set to none." http://api.jquery.com/fadeOut/

Or you could not use the jQuery library because there are already simple cross-browser JavaScript methods.