Lazy loading practice --js picture lazy loading and optimization

I. Introduction

Why would you use lazy loading of the picture? We begin to talk about this problem for a page is affecting shelf ah speed is the biggest picture, a general picture can reach the size 4-5M, and code compression also only a few dozen KB. When the page image too much time, page loading speed is very slow, a few seconds to load a page is not completed, the user experience is not good, it will lose a lot of users.

So much for the picture page, you can order to speed up page loading speed, we need a lot of time in the viewable area of ​​the picture does not appear within the first page does not load until scroll to the viewing area when recording again loaded. For this way will be greatly improved page load performance, it will improve the user experience.

 

Second, the principle

1, the img src tag pointing to a page in small pictures or src is null,

2, and then define data-src attribute (this attribute can customize the name, I only use data-src) attribute points to the real picture.

3, src points to a default picture, or when src is empty will be like server sends a request (default point to a picture of it only needs to request one). You can point to the address of loading.

4, when the page is loaded, first data-src attribute value of the tag img visual zone region is assigned to src.

5, then listens for the scroll event, load the user will see the picture (height + from the top of the visible area of ​​the height from <scroll bar appears at the top of the picture when use).

Note: To specify the width and height of the picture

 

For various width of the window, gives a good view of the Internet.

 

Third, the picture lazy loading implementation code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        img {
            display: block;
            margin-bottom: 50px;
            width: 800px;
            height: 400px;
        }
    </style>
</head>
<body>
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg6.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg7.png" alt="">
    <img src="" data-src="http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg" alt="">
    <img src="" data-src="http://cover.read.duokan.com/mfsv2/download/fdsc3/p01N203pHTU7/Wr5314kcLAtVCi.jpg!t" alt="">
    <img src="" data-src="http://77fkxu.com1.z0.glb.clouddn.com/20160308/1457402219_73571.jpg" alt="">
    <img src="" data-src="http://pic1.cxtuku.com/00/16/18/b3809a2ba0f3.jpg" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg9.png" alt="">
    <img src="" data-src="http://cover.read.duokan.com/mfsv2/download/fdsc3/p015trgKM7vw/H0iyDPPneOVrA4.jpg!t" alt="">
    <img src="" data-src="http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg8.png" alt="">
    <img src="" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg9.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg10.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg11.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg15.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg16.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg17.png" alt="">
<script>
    (function(){
    let num = document.getElementsByTagName('img').length;
    let img = document.getElementsByTagName("img");
    let n = 0; //存储图片加载到的位置,避免每次都从第一张图片开始遍历
    lazyload(); //页面载入完毕加载可是区域内的图片
     window.onscroll = lazyload;
    function lazyload() { //监听页面滚动事件
        let seeHeight = document.documentElement.clientHeight; //可见区域高度
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度
        for (let i = n; i < num; i++) {
            // 图片未出现时距离顶部的距离大于滚动条距顶部的距离+可视区的高度
            if (img[i].offsetTop < seeHeight + scrollTop) {
                if (img[i].getAttribute("src") == "") {
                    img[i].src = img[i].getAttribute("data-src");
                }
                n = i + 1;
            }
        }
    }
    })()

</script>
</body>
</html>

 

Fourth, the use of a throttle function optimization

If the function is directly bound to the scroll event, when the page is scrolled, the function will be triggered high frequency, which is affecting the performance of the browser.

As well as the following scene is often due to the frequent event is triggered, so frequently re-execute behavior dom operation, resource loading, leading to even pause browser UI Ben collapse.

1, resize, scroll event of the window object;

2, mousemove event of a drag;

3, shooting game mousedown, keydown events;

4, text input, keyup event done automatically;

There are ways to shake and the throttle way to solve this problem:

1. Stabilize principle : When the call to action n milliseconds, will be implemented, if n milliseconds within which in turn calls this action is re-calculated execution time.

Inadequate : when I have to scroll down the mouse, lazyload function will continue to be delayed, so that only came to a stop will be executed, then the need for timely show some circumstances, it is not so friendly

2, throttling principle : a pre-execution cycle, if the cycle is complete function have not yet triggered, it will perform a function; if this cycle is not over function is triggered, then the timer will reset and begin a new cycle .

Achieve the desired effect, neither frequent nor execution delay execution

 

Fifth, use the throttle function of the picture lazy loading code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        img {
            display: block;
            margin-bottom: 50px;
            width: 800px;
            height: 400px;
        }
    </style>
</head>
<body>
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg6.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg7.png" alt="">
    <img src="" data-src="http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg" alt="">
    <img src="" data-src="http://cover.read.duokan.com/mfsv2/download/fdsc3/p01N203pHTU7/Wr5314kcLAtVCi.jpg!t" alt="">
    <img src="" data-src="http://77fkxu.com1.z0.glb.clouddn.com/20160308/1457402219_73571.jpg" alt="">
    <img src="" data-src="http://pic1.cxtuku.com/00/16/18/b3809a2ba0f3.jpg" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg9.png" alt="">
    <img src="" data-src="http://cover.read.duokan.com/mfsv2/download/fdsc3/p015trgKM7vw/H0iyDPPneOVrA4.jpg!t" alt="">
    <img src="" data-src="http://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg8.png" alt="">
    <img src="" data-src="http://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg9.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg10.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg11.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg15.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg16.png" alt="">
    <img src="" data-src="https://www.mwcxs.top/static/staticImage/sliders/bg17.png" alt="">
<script>
    (function(){
    let num = document.getElementsByTagName('img').length;
    let img = document.getElementsByTagName("img");
    let n = 0; //存储图片加载到的位置,避免每次都从第一张图片开始遍历
    lazyload(); //页面载入完毕加载可是区域内的图片
    function lazyload() { //监听页面滚动事件
        let seeHeight = document.documentElement.clientHeight; //可见区域高度
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度
        for (let i = n; i < num; i++) {
            // 图片未出现时距离顶部的距离大于滚动条距顶部的距离+可视区的高度
            if (img[i].offsetTop < seeHeight + scrollTop) {
                if (img[i].getAttribute("src") == "") {
                    img[i].src = img[i].getAttribute("data-src");
                }
                n = i + 1;
            }
        }
    }
    //采用了节流函数
        function throttle(fun, delay, time) {
    let timeout,
        startTime = new Date();
    return function() {
        let context = this,
            args = arguments,
            curTime = new Date();
        clearTimeout(timeout);
        // 如果达到了规定的触发时间间隔,触发 handler
        if (curTime - startTime >= time) {
            fun.apply(context, args);
            startTime = curTime;
            // 没达到触发间隔,重新设定定时器
        } else {
            timeout = setTimeout(fun, delay);
        }
    };
};
window.addEventListener('scroll',throttle(lazyload,500,1000));
    })()
</script>
</body>
</html>

 

[Thank reading and subsequent starting new articles: sau exchange learning communities: https://www.mwcxs.top/ ]

Guess you like

Origin blog.csdn.net/saucxs/article/details/91968063