views:

44

answers:

3

Hi! I m trying to execute some code when image is not loaded. I m using following code:

<script language="javascript">

object = new Image();
object.src = '$imageurl';

if(!object.complete)
{
    //do something
}

</script>

But this is not working in Facebook. Please help me.

+1  A: 

Use the onload event which fires when image has been loaded like this:

object.onload = function(){
  // image has been loaded
};

Also have a look at:

Update:

To run code unless image has not been loaded, you could do this way:

<script language="javascript">

object = new Image();

// here image is not loaded yet

object.onload = function(){
  // image has been loaded
};

// image loaded, show it
object.src = '$imageurl';

</script>

I suspect you are using php by seeing $imageurl, you need to replace the line:

object.src = '$imageurl';

With:

object.src = '<?php echo $imageurl;?>';
Sarfraz
Re `object.src = '$imageurl';`: it is possible that (s)he is using a <a href="http://php.net/heredoc">heredoc</a>, thus negating the need for `<?php echo`, but judging by the user name, I'd say that was unlikely.
janmoesen
@janmoesen: I can't judge from the username :) but I pointed out just in case :) And even with heredoc it should be like `{$imageurl}`.
Sarfraz
A: 

You can use the onLoad event

<script language="javascript">

object = new Image();
object.src = '$imageurl';

object.onLoad = imageHasLoaded();

</script>
Marko
I want to execute code when image is not loaded.
A: 

Run a function using window.setInterval while the image is loading and stop it as soon as it has loaded.

function () {
var img = new Image();

var intervalId = window.setInterval(function () {
  /* stuff to do with "img" while it is loading */
}, 250);

img.onload = function () { window.clearInterval(intervalId); }
img.src = 'http://example.com/image.jpg';
}
janmoesen