We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
图片懒加载原理及如何实现
The text was updated successfully, but these errors were encountered:
图片懒加载其实就是用一个自定义属性存储图片的src,当且仅当图片出现或进入可视范围才去加载它。 下面是两种方法实现图片懒加载:
/* getBoundClientRect 的实现方式,监听 scroll 事件 */ let imgList = [...document.querySelectorAll('img')]; let num = imgList.length; let lazyLoad = (function() { let count = 0; return function() { let deleteIndexList = []; imgList.forEach((img, index) => { let rect = img.getBoundingClientRect(); if (rect.top < window.innerHeight) { img.src = img.dataset.src; deleteIndexList.push(index); count++; if (count === num) { document.removeEventListener( 'scroll', lazyLoad ); } } }); imgList = imgList.filter( (_, index) => !deleteIndexList.includes(index) ); }; })();
/* intersectionObserver 实现方式,实例化一个 IntersectionObserver,并使其观擦所有 img 标签 */ let imgList = [...document.querySelectorAll('img')]; let lazyLoad = function() { let observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.intersectionRatio > 0) { entry.target.src = entry.target.dataset.src; observer.unobserve(entry.target); } }); }); imgList.forEach(img => { observer.observe(img); }); };
intersectionObserver 详情请看: https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver
Sorry, something went wrong.
No branches or pull requests
图片懒加载原理及如何实现
The text was updated successfully, but these errors were encountered: