views:

720

answers:

8

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?

+9  A: 

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.

redsquare
Please correct the link, because it links to this answer...
Robert Koritnik
A: 

Yes, the code in your question works as long as you run it before the image has loaded.

svinto
A: 

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');" />
lance
but its jQuery, unobtrusive. Inline js events are a no no
redsquare
+2  A: 
$('img.beacon').load()

Will not always work correctly, ussually I do this:

$.fn.imageLoad = function(fn){
    this.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>
Pim Jager
why $(this).get(0).naturalWidth and not this.naturalWidth?
redsquare
@redsquare, good point, never really though about that. (changed, but untested (although it should just work))
Pim Jager
Ah good. Do you get through lots of keyboards;)
redsquare
If i'm not mistaken, $(this).get(0) returns the DOM element, instead of a jQuery object
Jim Schubert
yeah the same as this on its own
redsquare
so no need to create a jq object with this just for the sake of getting the original this back out of it!
redsquare
@redsquare: exactly! (and for the keyboard stuff, I'm quite a loussy typist (and also english isn't my native language (but it's mostly the typing that goes wrong)))
Pim Jager
@Jim: yes $(this).get(0) == this
Pim Jager
Consider returning this at the end of imageLoad() so that you can chain. `$('img.beacon').imageLoad(function() { /* good */ }).error(function() { /* bad */ })`
jhs
+1  A: 

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

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

I don't know exactly how your page is set up but remember that this needs to either be put in a .ready block or appear after the img tag in question.

theIV
Is what I said not correct?
theIV
+1  A: 
   <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 programatically anyway.

FerrousOxide
A: 

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.

a6hi5h3k
I don't think it does it this way, but you can check it out yourself... And doing it the way you did it is plain wrong. You don't use event binding that is **the proper** way of event handling.
Robert Koritnik