博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Javascript] IntersectionObserver -- Lazy Load Images on a Website
阅读量:5999 次
发布时间:2019-06-20

本文共 2287 字,大约阅读时间需要 7 分钟。

When it comes to websites performance is king. How long it takes for a page to load can mean the difference of millions of dollars for large ecommerce sites. In this lesson we'll use the IntersectionObserver to check when an image is in the viewport to defer loading the image.

document.addEventListener('DOMContentLoaded', () => {      const lazyImages = Array.from(document.querySelectorAll('img.lazy'));      if ('IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype) {          // Define the observer          let lazyImageObserver = new IntersectionObserver((entries, observer) => {              entries.forEach((entry) => {                  // logic for handling interstion                  if (entry.isIntersecting) {                      let lazyImage = entry.target                      lazyImage.src = lazyImage.dataset.src                      lazyImage.srcset = lazyImage.dataset.srcset                      lazyImage.classList.remove('lazy')                      lazyImageObserver.unobserve(lazyImage)                  }              })          })          // What to observe          lazyImages.forEach(lazyImage => {              lazyImageObserver.observe(lazyImage)          })      } else {      }  })

 

 

We can add some Margin to preload image even before we scroll to the image:

let lazyImageObserver = new IntersectionObserver((entries, observer) => {              entries.forEach((entry) => {                  // logic for handling interstion                  if (entry.isIntersecting) {                      let lazyImage = entry.target                      lazyImage.src = lazyImage.dataset.src                      lazyImage.srcset = lazyImage.dataset.srcset                      lazyImage.classList.remove('lazy')                      lazyImageObserver.unobserve(lazyImage)                  }              })          }, {             rootMargin: '50px'          })

rootMargin  Margin around the root. Can have values similar to the CSS  property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). The values can be percentages. This set of values serves to grow or shrink each side of the root element's bounding box before computing intersections. Defaults to all zeros.

转载地址:http://yyzmx.baihongyu.com/

你可能感兴趣的文章
Jfinal 学习控制台打印方法
查看>>
AngularJs初识
查看>>
带着三个问题深入浅出React高阶组件
查看>>
点石成金-Linux目录结构,命令,文件类型学习
查看>>
16. php-fpm配置相关
查看>>
处理图形中的乱码
查看>>
安装软件包
查看>>
linux磁盘分区丶挂载和卸载与格式化
查看>>
cobbler简概
查看>>
Objective-C中runtime机制的应用
查看>>
Tomcat日志中文乱码问题解决
查看>>
云搜索服务在日志解决方案的应用
查看>>
Jersey 2.x 分支 Java SE 兼容性
查看>>
PHP执行效率高zblog-asp为什么还有生存的空间?[图]
查看>>
国内有哪些可在室内外都能使用的激光雷达?
查看>>
zabbix的组件及作用 理论
查看>>
华为荣耀手机录制视频 华为手机如何录制视频
查看>>
商业化新路径?谷歌用AI提高风力发电效率
查看>>
红米手机5获取Root超级权限的步骤
查看>>
iOS开发网络篇—GET请求和POST请求
查看>>