IntersectionObserver 图片懒加载
参考:
- http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html
- https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver
<ul>
<li>
<img src="./assets/images/zhanwei.jpg" data-src="./assets/images/1.jpeg">
</li>
<li>
<img src="./assets/images/zhanwei.jpg" data-src="./assets/images/2.jpeg">
</li>
<li>
<img src="./assets/images/zhanwei.jpg" data-src="./assets/images/3.jpeg">
</li>
<li>
<img src="./assets/images/zhanwei.jpg" data-src="./assets/images/4.jpeg">
</li>
<li>
<img src="./assets/images/zhanwei.jpg" data-src="./assets/images/5.jpeg">
</li>
<li>
<img src="./assets/images/zhanwei.jpg" data-src="./assets/images/6.jpg">
</li>
<li>
<img src="./assets/images/zhanwei.jpg" data-src="./assets/images/7.jpg">
</li>
</ul>
var oBox = document.getElementsByTagName('img')
var io = new IntersectionObserver((changes) => {
changes.forEach((change) => {
if (change.intersectionRatio > 0) {
var container = change.target
var url = container.getAttribute('data-src')
if (url) {
container.src = url
container.setAttribute('data-src', '')
io.unobserve(container)
}
}
})
})
Array.from(oBox).forEach((item) => {
io.observe(item)
})