Lazy loading of pictures

Time:2022-5-25

Title of this article: realizing lazy loading of pictures
Author: Jake
Release time: November 26, 2016, 18:46:34
Last update: 12-28, 2016
Original link:http://i.jakeyu.top/2016/11/26/ Lazy loading of pictures/
License agreement: “signature – non commercial – sharing 4.0 in the same way” reprint, please keep the original link and author.

Meaning of lazy loading (why use lazy loading)

The biggest impact on the page loading speed is the image. An ordinary image can reach the size of a few m, while the code may be only tens of KB. When there are many pictures on the page, the loading speed of the page is slow. If the page is not loaded within a few seconds, many users may be lost.

Therefore, for pages with too many pictures, in order to speed up the page loading speed, we often need to not load the pictures that do not appear in the visual area in the page, and then load them after scrolling to the visual area. This will greatly improve the page loading performance and improve the user experience.

principle

Point the IMG tag Src in the page to a small picture or the SRC is empty, and then definedata-src(this attribute can be named by user before I use data SRC) attribute to point to the real image.srcPoint to a default picture, otherwise whensrcWhen empty, a request will also be sent to the server. Can pointloadingYour address.

Note: the width and height of the picture should be specified

<img src="https://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg" />

When loading the page, first put the IMG tag in the visual areadata-srcAttribute value negative tosrcThen, monitor the scrolling event and load the image that the user will see. This enables lazy loading.

code

Before writing code, you need to understand various heights. Look at this article firstscrollTop,offsetTop,scrollLeft,offsetLeft

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        img {
            display: block;
            margin-bottom: 50px;
            width: 400px;
            height: 400px;
        }
    </style>
</head>

<body>

    <img src="https://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg">
    <img src="https://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg">
    <img src="https://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg">
    <img src="https://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg">
    <img src="https://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg">
    <img src="https://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg">
    <img src="https://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg">
    <img src="https://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg">
    <img src="https://ww1.sinaimg.cn/large/006y8mN6gw1fa7kaed2hpj30sg0l9q54.jpg">
    <img src="https://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg">
    <img src="https://ww4.sinaimg.cn/large/006y8mN6gw1fa5obmqrmvj305k05k3yh.jpg">

</body>

JavaScript

<script>
    var num = document.getElementsByTagName('img').length;
    var img = document.getElementsByTagName("img");
    var n = 0; // Store the location where the picture is loaded to avoid traversing from the first picture every time

    lazyload(); // After the page is loaded, the pictures in the loading area can be loaded

    window.onscroll = lazyload;

    Function lazload() {// listen for page scrolling events
        var seeHeight = document. documentElement. clientHeight; // Height of visible area
        var scrollTop = document. documentElement. scrollTop || document. body. scrollTop; // Height of scroll bar from top
        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;
            }
        }
    }
</script>

jQuery

<script>
    var n = 0,
        imgNum = $("img").length,
        img = $('img');

    lazyload();

    $(window).scroll(lazyload);

    function lazyload(event) {
        for (var i = n; i < imgNum; i++) {
            if (img.eq(i).offset().top < parseInt($(window).height()) + parseInt($(window).scrollTop())) {
                if (img.eq(i).attr("src") == "default.jpg") {
                    var src = img.eq(i).attr("data-src");
                    img.eq(i).attr("src", src);

                    n = i + 1;
                }
            }
        }
    }
</script>

Performance optimization using throttling function

If you bind a function directly toscrollThis will affect the performance of the page scrolling function when it is triggered very frequently.

I want to limit the trigger frequency to optimize performance.

Throttling function: only one function is allowed to execute once in N seconds. Here is a simple throttling function:

//Simple throttling function
//Func function to execute
//Delay delay
//Time must be executed once within time
function throttle(fun, delay, time) {
    var timeout,
        startTime = new Date();

    return function() {
        var context = this,
            args = arguments,
            curTime = new Date();

        clearTimeout(timeout);
        //If the specified trigger time interval is reached, trigger the handler
        if (curTime - startTime >= time) {
            fun.apply(context, args);
            startTime = curTime;
            //If the trigger interval is not reached, reset the timer
        } else {
            timeout = setTimeout(fun, delay);
        }
    };
};
//The handler that you actually want to bind to the scroll event
function lazyload(event) {
        for (var i = n; i < imgNum; i++) {
            if (img.eq(i).offset().top < parseInt($(window).height()) + parseInt($(window).scrollTop())) {
                if (img.eq(i).attr("src") == "default.jpg") {
                    var src = img.eq(i).attr("data-src");
                    img.eq(i).attr("src", src);

                    n = i + 1;
                }
            }
        }
    }
//Throttling function is adopted
window.addEventListener('scroll',throttle(lazyload,500,1000));

Recommended Today

Digital DP-902. Number combinations up to N

Problem Description Given an array digits of digits in non-decreasing order. A number you can write with digits[i] any number of times. For example, if digits = ['1','3','5'], we can write digits like '13', '551', and '1351315'. Returns the number of positive integers that can be generated that are less than or equal to the […]