Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 580
Anurag Ratna Avatar asked May 14 '14 14:05

Anurag Ratna


People also ask

Is it mandatory to use src attribute in the image tag to specify the image location?

The src attribute is required, and contains the path to the image you want to embed.

Can img src be empty?

Use the getAttribute() method to check if an image src is empty, e.g. img. getAttribute('src') . If the src attribute does not exist, the method returns either null or empty string, depending on the browser's implementation.

Why is the src attribute necessary in an IMG tag?

The required src attribute specifies the URL of the image.


1 Answers

This is a bug in IE. According to the spec:

The IDL attribute complete must return true if any of the following conditions is true:

  • The src attribute is omitted.
  • The final task that is queued by the networking task source once the resource has been fetched has been queued.
  • The img element is completely available.
  • The img element is broken.

Otherwise, the attribute must return false.

The best way to know the state of an image, is to handle the load and error events. If that isn't feasible, for whatever reason, to tell if an image has loaded successfully, check for img.complete && img.naturalWidth > 0. If true, the image has loaded successfully. Otherwise, the image is either still loading, or has failed to load - it's difficult to tell which because of IE's inconsistency.

like image 184
gilly3 Avatar answered Nov 14 '22 22:11

gilly3