18910140161

js如何判断图片是否已加载

顺晟科技

2021-07-09 11:25:44

171

尽量为webAPI,或者第三方库的API

图片有个 onload 事件,触发就表示图片已加载。还有个 onerror 事件,触发就代表图片加载失败,一般会在 onerror 事件里面补一个错误图片。

<div class="imgdv">

    <img src="1.jpg" >
    <img src="2.jpg" >
    <img src="3.jpg" >

</div>$('img').onload = function() {

    //code

}$(function () { $(".imgdv").each(function() {

    var img = $(this);
    img.load(function () {
        img.attr("isLoad", "true");
    });
    img.error(function() {

    });

});});

<img> 元素在 JS 中对应 HTMLImageElement 接口,含有一个 complete 属性,表示该图片元素是否完成加载。不论是图片 error 了还是成功显示了都为 true

结合同接口的 naturalWidthnaturalHeight 属性可以判断图片是否成功展示。这两个属性在图片未加载或加载失败时同为 0 。一般来说只要结合一个是否为 0 就好了。

结合 <picture><source> 元素加载的图片也只需要读取对应的 <img> 元素上述属性就可以了。

... the source element's src attribute has no meaning when the element is nested within a picture element, ... the picture element itself does not display anything; it merely provides a context for its contained img element that enables it to choose from multiple URLs.—— Note in The picture element | HTML Standard

对于从 <object> 载入的图片则没有上述等价属性可以使用。如果该 <object> 元素有子节点,可以根据 <object> 元素仅在加载目标对象失败时显示子节点的特性,以类似于 .firstElementChild.offsetParent 是否为 null 这样的方式判断图片是否加载失败。

更常见更精细的判断需要通过事件侦听实现。

相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航