当前位置:网站首页>Lazy loading scheme of pictures

Lazy loading scheme of pictures

2022-07-05 10:44:00 Code Bruce Lee

Image lazy loading scheme
Preface
Lazy image loading is one of the important aspects of front-end performance improvement , Its main purpose is : Reduce network load , Enhance the experience .
But in order to influence the experience , You need to write the best layout style , It's best to write a bitmap .
Principle of lazy loading
In fact, the loading of pictures is mainly due to the src Caused by the , And if we want to implement lazy loading , Just avoid src Load the path , We can store the path of the picture to data-src On the user-defined data attribute , Then load on demand when needed .
There are two ways to implement on-demand loading : Here we focus on the first , At present, it is on the mobile end and pc Most of the waterfall flow patterns are the first .
1 Scroll to the bottom of the page to load
2 Paging load
Scroll to the bottom of the page to load the principle
The original way : Rolling monitoring
Its main principle is to monitor rolling events , When the scroll bar height is found + The height of the scroll bar is equal to document Altitude time , Is to reach the bottom of the page , When you need to reload pictures .

KaTeX parse error: Expected '}', got 'EOF' at end of input: …ction(){   if((window).scrollTop() + ( w i n d o w ) . h e i g h t ( ) > = (window).height()>= (window).height()>=(document).height()){

var $div = ‘

  • append Added node
  • ’;
    
    KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲container').app…div)
    
     }
    
    });
    A new way :IntersectionObserver
    Let's go check it out jq Of lazyload How to write this part of the function in the source code of , The core is dependence IntersectionObserver, Is to detect whether the element enters the view , If there's access , Then it will be removed lazy Of class, Its source code address : link
    
    document.addEventListener(“DOMContentLoaded”, function() {
    
    var lazyImages = [].slice.call(document.querySelectorAll(“img.lazy”));
    

    
    if (“IntersectionObserver” in window) {
    
    let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
    
    entries.forEach(function(entry) {
    
    if (entry.isIntersecting) {
    
    let lazyImage = entry.target;
    
    lazyImage.src = lazyImage.dataset.src;
    
    lazyImage.srcset = lazyImage.dataset.srcset;
    
    lazyImage.classList.remove(“lazy”);
    
    lazyImageObserver.unobserve(lazyImage);
    
    }
    
    });
    
    });
    

    
    lazyImages.forEach(function(lazyImage) {
    
    lazyImageObserver.observe(lazyImage);
    
    });
    
    } else {
    
    // Possibly fall back to a more compatible method here
    
    }
    
    });

原网站

版权声明
本文为[Code Bruce Lee]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051020548797.html