Published on

背景图懒加载

Authors
  • avatar
    Name
    duluwa.com
    Twitter
<div class="lazy-bg"></div>
.lazy-bg {
  background-image: none !important;
}
var lazyBackground = function () {
  var className = 'lazy-bg'

  var intersectionObserver = new IntersectionObserver(
    function (entries) {
      entries.forEach(function (entry) {
        if (entry.intersectionRatio > 0) {
          entry.target.classList.remove(className)
          intersectionObserver.unobserve(entry.target)
        }
      })
    },
    { rootMargin: '300px' }
  )

  var targetList = document.querySelectorAll('.' + className)
  targetList.forEach(function (el) {
    intersectionObserver.observe(el)
  })
}

window.addEventListener('load', function () {
  lazyBackground()
})