Why implement lazy loading? ? What are the benefits? The principle of lazy loading of pictures? ?

The lazy loading we saw before is generally in the form:

. Browse a webpage and prepare to drag the scroll bar down
. Drag a placeholder picture to the window
. The placeholder picture is instantly replaced with the final picture.
Reason: For
example, there are many pictures in a page, such as Taobao, Jingdong homepage, etc., If so many requests are sent as soon as it comes up, the page loading will be very long. If the js files are placed at the bottom of the document, it happens that the head of the page relies on this js file, it will be difficult to handle. What's more terrible: the server may be overwhelmed by sending one hundred or eighty requests as soon as it comes up (it's not just one or two people visiting this page).

Therefore, the advantages are obvious: not only can the pressure on the server be reduced, but also the loaded page can be presented to the user faster (good user experience).
Principle: The
  Insert picture description here
  main realization idea:
  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 , Just let it load out

   <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="">

js, mainly implemented with jquery

 $(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()

Do you have any simpler ideas for implementation? ? ?

Guess you like

Origin blog.csdn.net/lqlq54321/article/details/106606563