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

浪尽此生 提交于 2019-12-10 14:59:57

问题


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.


回答1:


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";



回答2:


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.




回答3:


Empty img src like any href as a relative URL refers to a base URL, the URL of the document. @mplungjan posted good solution to actually check if and when it was loaded




回答4:


Returns a Boolean that is true if the browser has finished fetching the image, whether successful or not. It also shows true, if the image has no src value.



来源:https://stackoverflow.com/questions/23657424/why-image-complete-property-always-return-true-even-if-there-is-no-src-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!