在Internet Explorer中使用IntersectionObserver polyfill延迟加载img失败

时间:2018-05-31 19:00:52

标签: javascript internet-explorer intersection-observer

我试图在可用的情况下使用IntersectionObserver实现延迟加载图像,否则使用polyfill(按照建议使用here)。

+function ($, window, document, undefined) {
    var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));

var lazyLoadImage = function() {
    var lazyImageObserver = new IntersectionObserver(function(entries, observer) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                var lazyImage = entry.target;
                lazyImage.src = lazyImage.dataset.src;
                lazyImage.classList.remove("lazy");
                lazyImageObserver.unobserve(lazyImage);
            }
        });
    });

    lazyImages.forEach(function(lazyImage) {
        lazyImageObserver.observe(lazyImage);
    });
};

var lazyLoadImagePolyfill = function() {
    var active = false;

    if (active === false) {
        active = true;

        setTimeout(function() {
            lazyImages.forEach(function(lazyImage) {
                if ((lazyImage.getBoundingClientRect().top <= window.innerHeight
                     && lazyImage.getBoundingClientRect().bottom >= 0)
                     && getComputedStyle(lazyImage).display !== 'none') {
                         console.log('lazyImage:', lazyImage);
                         lazyImage.src = lazyImage.dataset.src;
                         lazyImage.classList.remove('lazy');

                         lazyImages = lazyImages.filter(function(image) {
                             return image !== lazyImage;
                         });

                        if (lazyImages.length === 0) {
                            document.removeEventListener('scroll', lazyLoadImagePolyfill);
                            window.removeEventListener('resize', lazyLoadImagePolyfill);
                            window.removeEventListener('orientationchange', 
                            lazyLoadImagePolyfill);
                    }
                }
            });
            active = false;
        }, 200);
    }
    document.addEventListener("scroll", lazyLoadImagePolyfill);
    window.addEventListener("resize", lazyLoadImagePolyfill);
    window.addEventListener("orientationchange", lazyLoadImagePolyfill);
};

document.addEventListener('DOMContentLoaded', function(){
    if ("IntersectionObserver" in window) {
        lazyLoadImage();
    } else {
        lazyLoadImagePolyfill();
    }
});
}(jQuery, window, document)

这种方法在我测试的所有浏览器中都能正常运行,IE除外。我在控制台中获得SCRIPT5007: Unable to get property 'src' of undefined or null reference;抛出错误的行是lazyImage.src = lazyImage.dataset.src;。但是,该行之前的console.log显示以下内容:

lazyImage: [object HTMLImageElement]
    "lazyImage:"
    <img class="lazy" src="placeholder.png" data-src="real-pic.jpg"></img>

请注意:我被要求不使用外部库或插件。任何想法为什么会发生这种情况以及如何纠正它?

1 个答案:

答案 0 :(得分:1)

每当我不能使用观察者时,我通常会使用in-view来做这类事情,但是你说你被要求不使用任何外部库或插件,所以我写了你这个代码在vanilla javascript中。 此代码将在IE9 =&lt;没有填料。

注意:请注意我没有对性能进行任何优化,例如,假设所有图片都已加载,请删除事件监听器等。

&#13;
&#13;
document.addEventListener('DOMContentLoaded', lazyLoadImagePolyfill);

function lazyLoadImagePolyfill() {
  var lazyLoadImages = Array.from(document.getElementsByClassName('lazy'));
  _loadImage();
  window.onscroll = _loadImage;

  function _loadImage() {
    for (let i = 0; i < lazyLoadImages.length; i += 1) {
      var img = lazyLoadImages[i];
      if (isVisible(img)) {
        showImage(img);
      }
    }
  }
}

function isVisible(element) {
  var {
    top,
    bottom
  } = element.getBoundingClientRect();
  var vHeight = (window.innerHeight || document.documentElement.clientHeight);
  return ((top > 0 || bottom > 0) && top < vHeight);
}

function showImage(img) {
  var src = img.getAttribute('data-src');
  if (!src) {
    return;
  }
  img.setAttribute('src', src);
  img.onload = function() {
    img.removeAttribute('data-src');
  };
}
&#13;
img {
  margin-bottom: 200px;
  min-height: 1px;
  width: 100%;
  display: block;
}

.container {
  display: flex;
  flex-wrap: wrap;
  width: 400px;
  margin: auto;
}
&#13;
<div class="container">
  <img class="lazy" data-src="http://www.facetheforce.today/han-old/400" alt="Han Solo Old">
  <img class="lazy" data-src="http://www.facetheforce.today/han/400" alt="Han Solo">
  <img class="lazy" data-src="http://www.facetheforce.today/luke-old/400" alt="Luke Old">
  <img class="lazy" data-src="http://www.facetheforce.today/luke/400" alt="Luke">
  <img class="lazy" data-src="http://www.facetheforce.today/han-old/400">
</div>
&#13;
&#13;
&#13;