码迷,mamicode.com
首页 > 其他好文 > 详细

图片懒加载

时间:2018-05-16 00:30:20      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:href   允许   add   doc   界面   rect   org   viewport   最好   

判断元素是否出现在界面中:

window.addEventListener(‘scroll‘, () => {
  const rect = elem.getBoundingClientRect();
  const inViewport = rect.bottom > 0 && rect.right > 0 &&
                     rect.left < window.innerWidth &&
                     rect.top < window.innerHeight;
});

  上述代码的问题在于每次调用 getBoundingClientRect 时都会触发回流,严重地影响了性能。在事件处理函数中调用( getBoundingClientRect )尤为糟糕,就算使用了函数节流(的技巧)也可能对性能没多大帮助。

  在2016年后,可以通过使用 Intersection Observer 这一 API 来解决问题。它允许你追踪目标元素与其祖先元素或视窗的交叉状态。此外,尽管只有一部分元素出现在视窗中,哪怕只有一像素,也可以选择触发回调函数:

const observer = new IntersectionObserver(callback, options);
observer.observe(element);

  此 API 被广泛地支持,但仍有一些浏览器需要 polyfill。尽管如此,它仍是目前最好的解决方案。

 

图片懒加载

标签:href   允许   add   doc   界面   rect   org   viewport   最好   

原文地址:https://www.cnblogs.com/hellohello/p/9043657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!