且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

异步加载图片

更新时间:2023-12-05 09:04:28

异步加载(延迟加载)内容的方法是不设置'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>