JavaScript: Know when an image is fully loaded
$('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>
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.
<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.