js- lazy front end of the load

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_36251118/article/details/88052883

Realization of ideas: first the path all the pictures stored in custom properties, reaching the position (distance from the top of the picture is less than scrolling through pages of distance + screen height of the viewport), the custom properties in the path to re-assign the picture path to the page display

   var num = document.getElementsByTagName('img').length;
    var img = document.getElementsByTagName("img");
    // 存储图片加载到的位置,避免每次都从第一张图片开始遍历
    var n = 0;
    // 页面载入完毕加载可视区域内的图片
    lazyload();                                
    window.onscroll = lazyload;
    // 监听页面滚动事件
    function lazyload() {
        // 可见区域高度
        var seeHeight = document.documentElement.clientHeight;
        // 滚动条距离顶部高度
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        for (var i = n; i < num; i++) {
            if (img[i].offsetTop < seeHeight + scrollTop) {
                if (img[i].getAttribute("src") == "default.jpg") {
                    img[i].src = img[i].getAttribute("data-src");
                }
                n = i + 1;
            }
        }
    }

Guess you like

Origin blog.csdn.net/qq_36251118/article/details/88052883