image.js 999 B

12345678910111213141516171819202122232425262728293031323334
  1. const images = document.querySelectorAll("img");
  2. function loadImage(src) {
  3. let p = new Promise(function (resolve, reject) {
  4. let img = new Image();
  5. img.onload = function () {//加载时执行resolve函数
  6. resolve(img);
  7. }
  8. img.onerror = function () {
  9. reject(src);
  10. }
  11. img.src = src;
  12. })
  13. return p;
  14. }
  15. // 传给IntersectionObserver的回调函数
  16. // 在目标元素能看见时触发一次,目标元素看不见了时再触发一次
  17. const observer = new IntersectionObserver(entries => {
  18. entries.forEach(async entry => {
  19. if (entry.isIntersecting) {
  20. const image = entry.target;
  21. const data_src = image.getAttribute("data-src");
  22. let p = await loadImage(data_src)
  23. image.setAttribute("src", p.src);
  24. // 图片被加载后取消观察
  25. observer.unobserve(image);
  26. }
  27. });
  28. });
  29. images.forEach(image => {
  30. observer.observe(image);
  31. });