12345678910111213141516171819 |
- const images = document.querySelectorAll("img");
- // 传给IntersectionObserver的回调函数
- // 在目标元素能看见时触发一次,目标元素看不见了时再触发一次
- const observer = new IntersectionObserver(entries => {
- entries.forEach(entry => {
- if (entry.isIntersecting) {
- const image = entry.target;
- const data_src = image.getAttribute("data-src");
- image.setAttribute("src", data_src);
- // 图片被加载后取消观察
- observer.unobserve(image);
- }
- });
- });
- images.forEach(image => {
- observer.observe(image);
- });
|