[英]How does a missing src attribute in an img tag behave across browsers?
I have a page with many images hidden inside a set of disclosures. 我有一个页面,其中包含许多隐藏在一系列披露内的图像。 When you click on the title of the section, the image (as well as other things) appears.
单击该部分的标题时,将显示图像(以及其他内容)。 So far so good.
到现在为止还挺好。 However, there are many of these images, which leads to ridiculous loading times, so I want to load them only when they need to be displayed.
但是,有很多这些图像,导致荒谬的加载时间,所以我只想在需要显示时加载它们。 When I open the section, I check whether the
src
of the image is set, and if it isn't, I set it and the image loads. 当我打开该部分时,我检查图像的
src
是否已设置,如果不是,我设置它并加载图像。 I have found, however, that if I omit the src
attribute of my <img>
, Javascript (in Chrome) considers it === ''
. 但是,我发现,如果我省略了我的
<img>
的src
属性,Javascript(在Chrome中)认为它是=== ''
。 It's identical to the empty string! 它与空字符串相同! I would have expected it to be
undefined
. 我本来以为它是
undefined
。
This is pretty nice, but it seems a bit too nice. 这很不错,但似乎有点太好了。 How do different browsers evaluate
img.src
when img
is an <img>
tag without a src
? 当
img
是没有src
的<img>
标签时,不同浏览器如何评估img.src
? If I check that img.src === ''
, is this safe on other browsers? 如果我检查
img.src === ''
,这在其他浏览器上是否安全?
You can simply check it like this: 您可以像这样检查:
if (!img.src) {
// need to set the .src property here
}
Since this checks for any falsey value, this will cover you no matter whether the browser returns null
, undefined
or ""
. 由于这会检查任何falsey值,无论浏览器是返回
null
, undefined
还是""
,这都将覆盖您。
FYI, I tried this jsFiddle in Firefox, Chrome and IE and they all returned the empty string for the .src
property, but checking for any falsey value as above will make your code more permissible if some older version of some browser has a slightly different idea. 仅供参考,我在Firefox,Chrome和IE中尝试了这个jsFiddle ,他们都返回了
.src
属性的空字符串,但如果某些浏览器的某些旧版本略有不同,则检查上述任何虚假值将使您的代码更容易被允许理念。
For all the modern browsers, an image with no SRC
is complete. 对于所有现代浏览器,没有
SRC
的图像是完整的。 But, according to IE, an image with no SRC
is not complete - is not loaded
. 但是,根据IE,没有
SRC
的图像不完整 - is not loaded
。 You could use getAttribute() to check if src
attribute exists. 您可以使用getAttribute()来检查
src
属性是否存在。 Like: 喜欢:
if( !img.getAttribute('src') ) {
//the img does not have src attribute
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.