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