异步加载图片 [英] load image asynchronous

查看:91
本文介绍了异步加载图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有如下图像标签:

If I have an image tag like the following:

<img src="myimage.jpg" />

,如果我添加异步":

<img async src="myimage.jpg" />

图片会异步加载吗?

推荐答案

异步加载(延迟加载)内容的方法是不设置'src'属性,然后执行在DOM就绪后加载图像的脚本启动.

The way to async load (lazy load) the content is to not set the 'src' attribute and then execute a script that loads the images once DOM-ready is launched.

 <img data-lazysrc='http://www.amazingjokes.com/images/20140902-amazingjokes-title.png'/>

和jQuery(或者也可以使用纯JavaScript)使用下面的代码(如此处 所示) em>):

and with jQuery (or possible with plain JavaScript too) use below code (as suggested here):

<script>  
function ReLoadImages(){
    $('img[data-lazysrc]').each( function(){
        //* set the img src from data-src
        $( this ).attr( 'src', $( this ).attr( 'data-lazysrc' ) );
        }
    );
}

document.addEventListener('readystatechange', event => {
    if (event.target.readyState === "interactive") {  //or at "complete" if you want it to execute in the most last state of window.
        ReLoadImages();
    }
});
</script>

这篇关于异步加载图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆