使用 Intersection Observer 实现图片延迟加

2018-06-20  本文已影响17人  _____西班木有蛀牙
<!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>使用 Intersection Observer 实现图片延迟加载</title>
    <link href="https://cdn.bootcss.com/materialize/1.0.0-beta/css/materialize.min.css" rel="stylesheet">
    <style>
        img {
            width: 100%;
            margin: 15px 0;
        }
    </style>
</head>

<body>
    <div class="container">
        <ul>
            <li>
                <img class="js-lazy-image" width="996" height="664" data-src="images/1.jpg" alt="">
            </li>
            <li>
                <img class="js-lazy-image" width="996" height="560" data-src="images/2.jpg" alt="">
            </li>
            <li>
                <img class="js-lazy-image" width="996" height="748" data-src="images/3.jpg" alt="">
            </li>
        </ul>
    </div>
    <script>
        function preloadImage(image) {
            image.setAttribute('src', image.dataset.src)
        }

        // Get all of the images that are marked up to lazy load 
        const images = document.querySelectorAll('.js-lazy-image');
        const config = {
            // If the image gets within 50px in the Y axis, start the download. 
            rootMargin: '50px 0px',
            threshold: 0.01
        };
        // If we don't have support for intersection observer, load the images immediately
        if (!'IntersectionObserver' in window) {
            console.log(123)
            Array.from(images).forEach(image => preloadImage(image));
        } else {
            // The observer for the images on the page 
            let observer = new IntersectionObserver(onIntersection, config);
            
            function onIntersection(entries) {
                // Loop through the entries
                entries.forEach(entry => {
                    // Are we in viewport? 
                    if (entry.intersectionRatio > 0) {
                        // Stop watching and load the image
                        observer.unobserve(entry.target);
                        preloadImage(entry.target);
                    }
                });
            }

            images.forEach(image => {
                observer.observe(image);
            });
        }
    </script>
</body>

</html>
上一篇 下一篇

猜你喜欢

热点阅读