当源代码由js设置时加载检查图像

Check image is loaded when source set by js?

本文关键字:加载 检查 图像 设置 源代码 js      更新时间:2023-09-26

当我从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 );
});

在页面加载上加载两个图像。将其放在标题中

试试这个:

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