Web Images native js implement lazy loading

I usually encounter when doing business official website picture too much, too slow to load problem, after today to ask my colleagues, and focus a little, use lazy loading Load picture, greatly reducing the page load time will now be specific Code sharing out for your reference, if there is something wrong place welcome message corrections (ps: html code only for the show and does not involve a specific page layout for the use of the html, css add their own)

 

html

        <ul>
                <li>
                    <a href="">
<div>
                             <! - Here is the key sentence img ->
                            < IMG class = "lazy_img" Data-the src = "Image Path" > 
</
div > < div > Name </ div > </ A > </ Li > </ UL >

 

js (recommended on the bottom end of the block or public projects)

< Script > 

    // Image lazily (as used to be added in front of the src img tag data-, and adding the class name for img lazy_img) 
    const lazyImgList = document.getElementsByClassName ( ' lazy_img ' ); 

    for (X of lazyImgList) { 

        the console.log (X); 
        const Observer =  new new IntersectionObserver ((Changes) => { 

            changes.forEach (Change => {
                 IF (change.isIntersecting) { 
                    const IMG = change.target;
                     // the console.log (); 
                    IMG .src= img.getAttribute('data-src');
                    observer.unobserve(img);
                }
            });
        })
        observer.observe(x);

    }


</script>

Guess you like

Origin www.cnblogs.com/yite/p/12167173.html