图片懒加载高性能实现(IntersectionObserver方法)
Posted peter-web
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片懒加载高性能实现(IntersectionObserver方法)相关的知识,希望对你有一定的参考价值。
页面img标签
<img class="lazy" src="placeholder-image.jpg" data-src="image-to-lazy-load-1x.jpg" data-srcset="image-to-lazy-load-2x.jpg 2x, image-to-lazy-load-1x.jpg 1x" alt="I‘m an image!">
JS实现
document.addEventListener("DOMContentLoaded", function() { var lazyImages = [].slice.call(document.querySelectorAll("img.lazy")); if ("IntersectionObserver" in window) { let lazyImageObserver = new IntersectionObserver(function(entries, observer) { entries.forEach(function(entry) { if (entry.isIntersecting) { let lazyImage = entry.target; lazyImage.src = lazyImage.dataset.src; lazyImage.srcset = lazyImage.dataset.srcset; lazyImage.classList.remove("lazy"); lazyImageObserver.unobserve(lazyImage); } }); }); lazyImages.forEach(function(lazyImage) { lazyImageObserver.observe(lazyImage); }); } else { // Possibly fall back to a more compatible method here } });
以上是关于图片懒加载高性能实现(IntersectionObserver方法)的主要内容,如果未能解决你的问题,请参考以下文章