一个最简单的图片懒加载

阐释了懒加载是如何实现的

Posted by Warden_Gfs on December 13, 2017

普通的懒加载是如何实现的?

懒加载的思路其实很简单,刚开始的时候不把图片的真实路径绑到单个<img>标签上,事先需要在这个标签上加上类似于data-src的属性,把真实的图片源绑定到这个上面。之后遍历整个DOM树,找到所有的<img>,判断该DOM元素是否在当前滚动的可见区域内,监听滚动事件,如果图片即将进入可视区,则把真实的图片源绑定到该src

<script>
    function isInSight(el) {
        var bound = el.getBoundingClientRect();
        var clientHeight = window.innerHeight;
        return bound.top <= clientHeight + 100;
    }


    var index = 0;
    function checkImgs() {
        var imgs = document.querySelectorAll('img');
        for (var i = index; i < imgs.length; i++) {
            imgs[i].style.width='100%';
            if (isInSight(imgs[i])) {
                loadImg(imgs[i]);
                index = i;
            }
        }
        // Array.from(imgs).forEach(el => {
        //   if (isInSight(el)) {
        //     loadImg(el);
        //   }
        // })
    }

    function loadImg(el) {
        console.log(el.src)
        if (el.src=='') {
            var source = el.dataset.src;
            el.src = source;
        }
    }

    function throttle(fn, mustRun = 500) {
        var timer = null;
        var previous = null;
        return function() {
            var now = new Date();
            var context = this;
            var args = arguments;
            if (!previous) {
                previous = now;
            }
            var remaining = now - previous;
            if (mustRun && remaining >= mustRun) {
                fn.apply(context, args);
                previous = now;
            }
        }
    }
    window.onload=checkImgs;
    window.onscroll = throttle(checkImgs);
</script>