前端开发

前端优化之lazy-load

2019-03-05  本文已影响0人  Chris__Liu

页面加载性能问题

最近我的BOSS说发现个问题,老项目打开的时候特别的卡,我仔细的研究了一下页面的结构,发现这个页面有很多图片要加载,我想到的方案就是用懒加载来实现性能的提升。

实现思路

JS方案

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>LozyLoad</title>
    <style>
        .images{
            display: flex;
            flex-direction: column;
            text-align: center;
            width: 500px;
        }
        .img-item{
            height:400px;
            width: 400px;
            margin: 20px;
        }

    </style>
</head>
<body>
    <div class="images">
        <img class="img-item" alt="loading" data-src="./img/1.png">
        <img class="img-item" alt="loading" data-src="./img/2.png">
        <img class="img-item" alt="loading" data-src="./img/3.png">
        <img class="img-item" alt="loading" data-src="./img/4.png">
        <img class="img-item" alt="loading" data-src="./img/5.png">
    </div>
    <script type="text/javascript">
        var imgs = document.querySelectorAll('img');
        var lazyload = function(){
            var scrollTop = document.body.scrollTop || document.documentElement.scrollTop
            var winTop = window.innerHeight
            for(var i=0;i < imgs.length;i++){
                if(imgs[i].offsetTop <= scrollTop + winTop ){
                    imgs[i].src = imgs[i].getAttribute('data-src')
                }
            }
        }
        function throttle(method,delay){
            let timer = null
            return function(){
                let args = arguments
                clearTimeout(timer)
                timer = setTimeout(function(){
                    console.log(this)
                    method.apply(this.args)
                },delay)
            }
        }
        lazyload()
        window.onscroll = throttle(lazyload,200)
    </script>

    <script type="text/javascript">
        //获取观察器实例  changes是被观察的对象数组
        var observer = new IntersectionObserver(function(changes){  
            console.log(changes);
            changes.forEach(function(index,item){
                if(item.intersectionRatio > 0 && item.intersectionRatio < 1)
                    //target:被观察的目标元素,是一个 DOM 节点对象
                    item.target.src = item.target.dataset.src;
            });
        });
        function addObserver(){
            var listItems = document.querySelectorAll('.img-item');
            listItems.forEach(function(item){
                //实例的observe方法可以指定观察哪个DOM节点
                //开始观察  observe的参数是一个 DOM 节点对象
                observer.observe(item);
            });
        }
        addObserver();
    </script>
    
</body>
</html>

Jquery方案

jquery_lazyload

Vue

vue-lazyload
vue-lazyload原理解析

React

react-lazyload

上一篇 下一篇

猜你喜欢

热点阅读