简体   繁体   中英

JavaScript: Know when an image is fully loaded

If I have a beacon:

<img src="http://example.com/beacon" />

I want a method to be called once the beacon request finishes. Something like:

<script>
    $("img.beacon").load(function() {
        // do stuff knowing the beacon is done
    });
</script>

Is it possible? Is it in jQuery?

Sure. Remember the load needs to be added before the src attribute.

$('<img />').load( function(){
  console.log('loaded');
}).attr('src', imgUrl);

If you have defined the image tag in the markup then your stuck with when the window load event fires to be sure the image has come down the wire.

$('img.beacon').load()

Will not always work correctly, ussually I do this:

$.fn.imageLoad = function(fn){
    this.on('load', fn);
    this.each( function() {
        if ( this.complete && this.naturalWidth !== 0 ) {
            $(this).trigger('load');
        }
    });
}

The above code also covers cases where the image has finished loading before the script is executed. This can happen when you define the image in the markup.

Use like this:

<img src='http://example.com/image.png' class='beacon' />
<script type='text/javascript'>
$(document).ready(function(){ //document.ready not really necessary in this case
   $('img.beacon').imageLoad(function(){
      //do stuff
   });
});
</script>
<script type="text/javascript">
    $().ready(function() {
        $('img#beacon').attr('src', 'http://sstatic.net/so/img/so/logo.png')
            .load(function() { alert('Image Loaded'); })
            .error(function() { alert('Error Loading Image');
        });
    });
</script>

This will load the StackOverflow logo.

If it loads successfully, the alert('Image Loaded'); is performed.
If it fails, the alert('Error Loading Image'); is performed.

Of course, either of these can be replaced with your own functions. As a new user, It refused my image tag but the image tag should only contain the id='beacon' attribute. unless you want to add a class. We're setting the src attribute in code here, typically images that you are monitoring for completion have src values that are set programmatically anyway.

Another option, if it suits you: The onload event occurs immediately after a page or an image is loaded.

Such as:

<img ... onload="alert('test');" />

Here's a simple javascript code that works on all browsers:

var myImage = new Image();

myImage.onload = function() {
    var image_width = myImage.width;
    var image_height = myImage.height;
    $('#pictureEl').html('<img width="'+ image_width +'" height="'+ image_height +'" src='+ myImage.src + '></img>');           
};

myImage.src = myUrl;

A jQuery snippet must be doing the same thing, under the hood.

You can do it easily in two way.lets see the ways:

1.Using onload attribute in img tag:

<img onload="alert('loaded');" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">

This will trigger alert just after the photo is finished loading.

2.Using EventListener in JavaScript:

document.getElementsByTagName("img").addEventListener("load", function loaded(){
  //any code you may need
  }); 

This code goes in your external js file or internal script tag.

You can do this for every individual img tag using class and id attributes.

You could use the onload event which fires when the entire page has finished loading.

$(window).load(function(){
  //everything is loaded
});

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