首页 > 解决方案 > 增加延迟加载检测的视口

问题描述

我正在使用这个脚本来延迟加载标签,我对其中的大部分内容都很熟悉,但有一个部分我不太确定

   document.addEventListener("DOMContentLoaded", function() {
     var lazyloadImages;

     if ("IntersectionObserver" in window) {
       lazyloadImages = document.querySelectorAll(".lazy");
       var imageObserver = new IntersectionObserver(function(entries, observer) {
         entries.forEach(function(entry) {
           if (entry.isIntersecting) {
             var image = entry.target;
             image.src = image.dataset.src;
             image.classList.remove("lazy");
             imageObserver.unobserve(image);
           }
         });
       });

       lazyloadImages.forEach(function(image) {
         imageObserver.observe(image);
       });
     } else {
       var lazyloadThrottleTimeout;
       lazyloadImages = document.querySelectorAll(".lazy");

       function lazyload () {
         if(lazyloadThrottleTimeout) {
           clearTimeout(lazyloadThrottleTimeout);
         }

         lazyloadThrottleTimeout = setTimeout(function() {
           var scrollTop = window.pageYOffset;
           lazyloadImages.forEach(function(img) {
               if(img.offsetTop < (window.innerHeight + scrollTop)) {
                 img.src = img.dataset.src;
                 // img.classList.remove('lazy');
               }
           });
           if(lazyloadImages.length == 0) {
             document.removeEventListener("scroll", lazyload);
             window.removeEventListener("resize", lazyload);
             window.removeEventListener("orientationChange", lazyload);
           }
         }, 20);
       }

       document.addEventListener("scroll", lazyload);
       window.addEventListener("resize", lazyload);
       window.addEventListener("orientationChange", lazyload);
     }
   })

目前,<img>如果它进入视口的底部,它将加载一个。我希望它提前加载 imgs,比如在视口下方 200 像素 - 300 像素,这样用户就不会看到加载的发生。

我认为这与这部分有关

if(img.offsetTop < (window.innerHeight + scrollTop))

我不知道这些值是什么意思,所以我不确定如何指定提前 200px 开始延迟加载。

干杯

标签: javascript

解决方案


试试这个:

if(img.offsetTop < (window.innerHeight + scrollTop + 250))

推荐阅读