简体   繁体   中英

Check image is loaded when source set by js?

How could i check that image is loaded when i am set image source from jquery. i want change image on mouse over and due large image size its taking time to loading so want to show loading image until it loads.

Here is my code snippet:

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

image1 is 436x436 and its taking time to load i want to show loading image before loading this image

Please help me...

use below code

 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.
});

you can use below function to get load callback for image :

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

Here's what I did on my site brother and it loads perfectly.

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 two images on page load.place it in header

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM