当 js 设置源时检查图像是否加载?

Check image is loaded when source set by js?

当我从 jquery 设置图像源时,如何检查图像是否已加载。我想在鼠标悬停时更改图像,并且由于图像尺寸较大,加载需要时间,所以我想在加载之前显示正在加载的图像。

这是我的代码片段:

timer = setInterval(function() {
selector.attr('src',  'localhost/product/image1.jpg');

图片 1 为 436x436,加载需要时间 我想在加载此图片之前显示加载图片

请帮帮我...

使用下面的代码

 selector.attr('src',  'localhost/product/image1.jpg');
 //show loader code here 
 var loadImage = new Image();
 loadImage.src = selector.attr('src');
  loadImage.onload = function(){
    // hide loader code here
 }
//show image on mouseenter event
img.addEventListener('mouseenter',function(){
    this.setAttribute('src',  'localhost/product/image1.jpg');
    //show loading image here
});
img.addEventListener('load',function(){
    //Image loaded. So remove loading image here.
});

您可以使用以下函数获取图像的加载回调:

$("#idOfImage").load(function() { /* image loaded */})
               .error(function() { /* error in loading */ });

这是我在我的网站兄弟上所做的,它加载完美。

HTML

<a href="#" full="http://www.sample.com/wp-content/uploads/2015/01/plot3picture.jpg">
    <img src="http://www.sample.com/wp-content/uploads/2015/01/plot3picture-150x150.jpg" alt="" />                
</a>

JS

$( window ).bind( 'load', function(){
    setTimeout( function(){ 
        $( 'body a' ).each( function(){
            $( this ).find( 'img' ).attr( 'src', $( this ).attr( 'full' ) ); 
        }); 
    }, 300 );
});

在 load.place 页面加载两张图片 header

试试这个:

if (document.images) {
    img1 = new Image();
    img1.src = "imgpath/image1.png";
    img2 = new Image();
    img2.src = "imgpath/image2.png"";
}