Search code examples
javascripthtmlimageinternet-explorer-11

Why Image 'complete' property always return true even if there is no src tag?


I just write

document.createElement("img").complete;//To check whether image is loaded or not

In Firefox,it returns true. In IE,it return false

OR

In a html page just create one image as:

 <!-- IMG tag with no SRC attribute. -->
<img id="noSrcImg" />

and In js check the complete property value :

var img = document.getElementById("noSrcImg");
img.complete

true for FF and false for IE

Can any one explain why this inconsistent behavior?

Is there any other better way to check whether image is loaded or not in DOM?

i tried with readyState attribute as well but its not available for IE11.


Solution

  • Please try load

    Also make sure the event handlers are defined BEFORE you assign src - on really fast networks, the src may load before the event handler if not defined first

    var im = document.createElement("img");
    im.onload=function() { alert(this.src+' loaded')} // assign before src
    im.onerror=function() { alert(this.src+' failed')} // if necessary
    im.src="someimage.jpg";