Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if an image has preloaded successfully? [duplicate]

Tags:

javascript

Possible Duplicate:
Check if an image is loaded (no errors) in JavaScript

After being loaded by javascript by setting img.src.

Thanks...!

like image 210
mtay Avatar asked Dec 06 '10 08:12

mtay


People also ask

How do you know if an image has loaded?

To determine whether an image has been completely loaded, you can use the HTMLImageElement interface's complete attribute. It returns true if the image has completely loaded and false otherwise. We can use this with naturalWidth or naturalHeight properties, which would return 0 when the image failed to load.

How do I know if my img src is valid?

To check if an img src is valid: Add an error event listener on the img element. If the src is invalid, set it to a backup image. Alternatively, hide the image.

How do you show image only when it is completely loaded?

Preload the image and replace the source of the <img /> after the image has finished loading. Show activity on this post. You can use the complete property to check if the image has finished loading.

How can you tell if an image is not loaded?

Using attributes of <img> to check whether an image is loaded or not. The attributes we will use are: onload: The onload event is triggered when an image is loaded and is executed. onerror: The onerror event is triggered if an error occurs during the execution.


1 Answers

You can use the load event like this:

var img = document.getElementById('imgID');

// or

var img = new Image;

img.onload = function(){
  alert('The image has been loaded');
  img.src = 'image path here';
};

Or when you use the load event of the window, images are loaded by then:

window.onload = function(){
  // everything is loaded now
};
like image 164
Sarfraz Avatar answered Sep 22 '22 00:09

Sarfraz