How to realize lazy loading of pictures? How to realize lazy loading of pictures?

1. What is lazy loading

Assign the picture src to a default picture first, when the user scrolls to the visible area picture, then load the subsequent real picture

2. Why introduce lazy loading

LazyLoad is an effective way of front-end optimization, which can reduce the pressure on the server, and can make the loaded page appear to the user faster (good user experience)

3. The principle of loading realization

First set the src link in the img tag to be empty, put the real image link in the custom attribute (data-src), when js monitors the image element to enter the visual window, store the address in the custom attribute To src, to achieve the effect of lazy loading.

4. Realization ideas

If the sum of the scroll size and the screen height is greater than the distance from the top of the element, set a timer to create a lazy loading effect, that is, when we slide the scroll bar and see the picture, let it load

5. Implementation of lazy loading (jquery)

   <img src="/image/8.jpg" data-src="/image/1.png" alt="">
    <img src="/image/8.jpg" data-src="/image/2.png" alt="">
    <img src="/image/8.jpg" data-src="/image/3.png" alt="">
    <img src="/image/8.jpg" data-src="/image/4.png" alt="">
    <img src="/image/8.jpg" data-src="/image/5.png" alt="">
    <img src="/image/8.jpg" data-src="/image/6.png" alt="">
    <img src="/image/8.jpg" data-src="/image/7.png" alt="">

 $(window).scroll(handleScroll)
    function handleScroll() {
    
    
        let imgs = $('img[data-src]');
        console.log(imgs)
        //获取滚动的值
        let bodyScrollHeight = document.body.scrollTop || document.documentElement.scrollTop
        console.log(bodyScrollHeight)
        //获取可视高度(屏幕高度)
        let windowHeight = window.innerHeight
        console.log(windowHeight)
        for (let i = 0; i < imgs.length; i++) {
    
    
             // 获取元素到浏览器顶部的距离
            let imgHeight = $(imgs[i]).offset().top
           // console.log(imgHeight)
           // 如果滚动的大小和屏幕高度之和大于元素到顶部的距离
            if (imgHeight < windowHeight + bodyScrollHeight) {
    
    
                //setTimeout:设置一个定时器,制造懒加载的延迟加载的效果
                setTimeout(function () {
    
    
                    $(imgs).eq(i).attr('src', $(imgs).eq(i).attr('data-src'))
                }, 1000)
            }
        }
    }
    handleScroll()

Primitive
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Lazyload</title>
    <style>
    img {
    
    
        display: block;
        margin-bottom: 50px;
        height: 200px;
    }
    </style>
</head>
<body>
    <img src="images/loading.gif" data-src="images/1.png">
    <img src="images/loading.gif" data-src="images/2.png">
    <img src="images/loading.gif" data-src="images/3.png">
    <img src="images/loading.gif" data-src="images/4.png">
    <img src="images/loading.gif" data-src="images/5.png">
    <img src="images/loading.gif" data-src="images/6.png">
    <img src="images/loading.gif" data-src="images/7.png">
    <img src="images/loading.gif" data-src="images/8.png">
    <img src="images/loading.gif" data-src="images/9.png">
    <img src="images/loading.gif" data-src="images/10.png">
    <img src="images/loading.gif" data-src="images/11.png">
    <img src="images/loading.gif" data-src="images/12.png">
    <script>
    function throttle(fn, delay, atleast) {
    
    //函数绑定在 scroll 事件上,当页面滚动时,避免函数被高频触发,
        var timeout = null,//进行去抖处理
        startTime = new Date();
        return function() {
    
    
             var curTime = new Date();
            clearTimeout(timeout);
            if(curTime - startTime >= atleast) {
    
    
              fn();
              startTime = curTime;
            }else {
    
    
                timeout = setTimeout(fn, delay);
            }
        }
    }
    function lazyload() {
    
    
        var images = document.getElementsByTagName('img');
        var len    = images.length;
        var n      = 0;      //存储图片加载到的位置,避免每次都从第一张图片开始遍历        
        return function() {
    
    
            var seeHeight = document.documentElement.clientHeight;
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            for(var i = n; i < len; i++) {
    
    
                if(images[i].offsetTop < seeHeight + scrollTop) {
    
    
                    if(images[i].getAttribute('src') === 'images/loading.gif') {
    
    
                       images[i].src = images[i].getAttribute('data-src');
                    }
                  n = n + 1;
                }
            }
        }
    }
    var loadImages = lazyload();
    loadImages();          //初始化首页的页面图片
    window.addEventListener('scroll', throttle(loadImages, 500, 1000), false);
  //函数节流(throttle)与函数去抖(debounce)处理,
//500ms 的延迟,和 1000ms 的间隔,当超过 1000ms 未触发该函数,则立即执行该函数,不然则延迟 500ms 执行该函数
    </script>
</body>
</html>

Reference link:
https://www.cnblogs.com/qing-5/p/11343125.html
https://blog.csdn.net/lqlq54321/article/details/106606563/

Guess you like

Origin blog.csdn.net/weixin_43956521/article/details/111060811