手撕懒加载

2019-09-11
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <title>LazyLoad</title>
        <style>
            img {
                display: block;
                margin: 0 auto 100px;
                width: 680px;
                height: 810px;
            }
        </style>
    </head>
    <body>
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-pl/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-bd/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-cg/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-cy/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-gb/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-mj/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-tm/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-wd/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-cj/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-tc/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-cy/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-sl/per.png" alt="">
        <img src="" data-src="https://jx3.xoyo.com/zt/2014/11/21/zt/menpai/assets/images/mp-qx/per.png" alt="">

    </body>
    <script>
        var img = document.getElementsByTagName('img');

        //存储图片加载到的位置
        var n = 0;
        // 页面载入完毕加载可视区域内的图片
        lazyLoad();
        // 监听页面滚动事件
        window.onscroll = lazyLoad;

        function lazyLoad() {
            // 可视区高度
            //document.documentElement返回的是文档对象document的根元素的只读属性(如html元素)
            var viewHeight = document.documentElement.clientHeight;
            // 滚动条距离顶部的高度
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            for (var i = n; i < img.length; i++) {
                if (img[i].offsetTop < viewHeight + scrollTop) {
                    if (img[i].getAttribute('src') == '') {
                        img[i].src = img[i].getAttribute('data-src');
                    }
                    n = i + 1;
                }
            }
        }
    </script>
</html>

搞清clientHeight、offsetHeight、scrollHeight、offsetTop、scrollTop

原文链接:segmentfault.com

上一篇:promise封装AJAX,既可用callback也可用.then(较新版的jquery也是如此)
下一篇:七牛文件上传的前后端部署
相关教程
关注微信

扫码加入 JavaScript 社区

相关文章

首次访问,需要验证
微信扫码,关注即可
(仅需验证一次)

欢迎加入 JavaScript 社区

号内回复关键字:

回到顶部