{"id":19322918,"url":"https://github.com/leo555/lazyload","last_synced_at":"2026-06-15T03:32:24.025Z","repository":{"id":144046033,"uuid":"101613914","full_name":"Leo555/lazyload","owner":"Leo555","description":"Lazyload demo","archived":false,"fork":false,"pushed_at":"2018-05-05T04:45:13.000Z","size":10495,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-24T05:45:26.541Z","etag":null,"topics":["intersectionobserver","lazyload"],"latest_commit_sha":null,"homepage":"https://lz5z.com/lazyload","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Leo555.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-08-28T07:01:56.000Z","updated_at":"2018-05-05T04:37:35.000Z","dependencies_parsed_at":"2023-05-02T14:58:09.138Z","dependency_job_id":null,"html_url":"https://github.com/Leo555/lazyload","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Leo555/lazyload","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Leo555%2Flazyload","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Leo555%2Flazyload/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Leo555%2Flazyload/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Leo555%2Flazyload/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Leo555","download_url":"https://codeload.github.com/Leo555/lazyload/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Leo555%2Flazyload/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34346867,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-15T02:00:07.085Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["intersectionobserver","lazyload"],"created_at":"2024-11-10T01:43:03.686Z","updated_at":"2026-06-15T03:32:24.011Z","avatar_url":"https://github.com/Leo555.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# lazyload\nLazyload demo\n\n[demo地址](https://lz5z.com/lazyload)\n\n## 懒加载\n\nLazyload 可以加快网页访问速度，减少请求，实现思路就是判断图片元素是否可见来决定是否加载图片。当图片位于浏览器视口 (viewport) 中时，动态设置 `\u003cimg\u003e` 标签的 src 属性，浏览器会根据 src 属性发送请求加载图片。\n\n## 懒加载实现\n\n首先不设置 src 属性，将图片真正的 url 放在另外一个属性 data-src 中，在图片即将进入浏览器可视区域之前，将 url 取出放到 src 中。\n\n懒加载的关键是**如何判断图片处于浏览器可视范围内**，通常有三种方法：\n\u003c!--more--\u003e\n\n### 方法一\n\n通过对比屏幕可视窗口高度和浏览器滚动距离与元素相对文档顶部的距离之间的关系，判断元素是否可见。\n\n\n示意图如下：\n\n\u003cimg src=\"./images/lazyload.svg\" alt=\"lazyload.svg\"\u003e\n\n代码如下：\n\n```javascript\nfunction isInSight(el) {\n    const clientHeight = window.innerHeight // 获取屏幕可视窗口高度\n    const scrollTop = document.body.scrollTop // 浏览器窗口顶部与文档顶部之间的距离\n    // el.offsetTop 元素相对于文档顶部的距离 \n    // +100是为了提前加载\n    return el.offsetTop \u003c= clientHeight + scrollTop + 100\n}\n```\n\n### 方法二\n\n通过 getBoundingClientRect() 获取图片相对于浏览器视窗的位置\n\n示意图如下：\n\n\u003cimg src=\"./images/lazyload1.svg\" alt=\"lazyload1.svg\"\u003e\n\ngetBoundingClientRect() 方法返回一个 ClientRect 对象，里面包含元素的位置和大小的信息\n\n```javascript\nClientRect {\n\tbottom: 596,\n\theight: 596,\n\tleft: 0,\n\tright: 1920,\n\ttop: 0,\n\twidth: 1920\n}\n```\n\n其中位置是相对于浏览器视图左上角而言。代码如下：\n\n```javascript\nfunction isInSight1(el) {\n    const bound = el.getBoundingClientRect() \n    const clientHeight = window.innerHeight // 表示浏览器可视区域的高度\n    // bound.top 表示图片到可视区域顶部距离\n    // +100是为了提前加载\n    return bound.top \u003c= clientHeight + 100 \n}\n```\n\n### 方法三\n\n使用 IntersectionObserver API，观察元素是否可见。“可见”的本质是目标元素与 viewport 是否有交叉区，所以这个 API 叫做“交叉观察器”。\n\n实现方式\n\n```javascript\nfunction loadImg(el) {\n    if (!el.src) {\n        const source = el.dataset.src\n        el.src = source\n        el.removeAttribute('data-src')\n    }\n}\n\nconst io = new IntersectionObserver(entries =\u003e {\n\tfor (const entry of entries) {\n        const el = entry.target\n        const intersectionRatio = entry.intersectionRatio\n        if (intersectionRatio \u003e 0 \u0026\u0026 intersectionRatio \u003c= 1) {\n            loadImg(el)\n        }\n        el.onload = el.onerror = () =\u003e io.unobserve(el)\n    }\n})\n\nfunction checkImgs() {\n    const imgs = Array.from(document.querySelectorAll('img[data-src]'))\n    imgs.forEach(item =\u003e io.observe(item))\n}\n```\n\n## IntersectionObserver\n\nIntersectionObserver 的作用就是检测一个元素是否可见，以及元素什么时候进入或者离开浏览器视口。\n\n### 兼容性\n\n- Chrome 51+（发布于 2016-05-25）\n- Android 5+ （Chrome 56 发布于 2017-02-06）\n- Edge 15 （2017-04-11）\n- iOS 不支持\n\n### Polyfill\n\nWICG 提供了一个 [polyfill](https://github.com/w3c/IntersectionObserver)\n\n### API\n\n```javascript\nconst io = new IntersectionObserver(callback, option)\n```\n\nIntersectionObserver 是一个构造函数，接受两个参数，第一个参数是可见性变化时的回调函数，第二个参数定制了一些关于可见性的参数（可选），IntersectionObserver 实例化后返回一个观察器，可以指定观察哪些 DOM 节点。\n\n下面是一个最简单的应用：\n\n```javascript\n// 1. 获取 img\nconst img = document.querySelector('img')\n// 2. 实例化 IntersectionObserver，添加 img 出现在 viewport 瞬间的回调\nconst observer =  new IntersectionObserver(changes =\u003e { \n  console.log('我出现了！') \n});\n// 3. 开始监听 img\nobserver.observe(img)\n```\n\n(1) callback\n\n回调 callback 接受一个数组作为参数，数组元素是 IntersectionObserverEntry 对象。IntersectionObserverEntry 对象上有7个属性，\n\n```javascript\nIntersectionObserverEntry {\n\ttime: 72.15500000000002, \n\trootBounds: ClientRect, \n\tboundingClientRect: ClientRect, \n\tintersectionRatio: 0.4502074718475342,\n\tintersectionRect: ClientRect, \n\tisIntersecting: true,\n\ttarget: img\n}\n```\n- boundingClientRect: 对 observe 的元素执行 getBoundingClientRect 的结果\n- rootBounds: 对根视图执行 getBoundingClientRect 的结果\n- intersectionRect: 目标元素与视口（或根元素）的交叉区域的信息\n- target: observe 的对象，如上述代码就是 img\n- time: 过了多久才出现在 viewport 内\n- intersectionRatio：目标元素的可见比例，intersectionRect 占 boundingClientRect 的比例，完全可见时为1，完全不可见时小于等于0\n- isIntersecting: 目标元素是否处于视口中\n\n(2) option\n\n假如我们需要特殊的触发条件，比如元素可见性为一半的时候触发，或者我们需要更改根元素，这时就需要配置第二个参数 option 了。\n\n通过设置 option 的 threshold 改变回调函数的触发条件，threshold 是一个范围为0到1数组，默认值是[0]，也就是在元素可见高度变为0时就会触发。如果赋值为 [0, 0.5, 1]，那回调就会在元素可见高度是0%，50%，100%时，各触发一次回调。\n\n```javascript\nconst observer =  new IntersectionObserver((changes) =\u003e { \n  console.log(changes.length); \n}, {\n  root: null, \n  rootMargin: '20px', \n  threshold: [0, 0.5, 1]\n});\n```\n\nroot 参数默认是 null，也就是浏览器的 viewport，可以设置为其它元素，rootMargin 参数可以给 root 元素添加一个 margin，如 `rootMargin: '20px'` 时，回调会在元素出现前 20px 提前调用，消失后延迟 20px 调用回调。\n\n(3) 观察器\n\n```javascript\n// 开始观察\nio.observe(document.getElementById('root'))\n\n// 观察多个 DOM 元素\nio.observe(elementA)\nio.observe(elementB)\n\n// 停止观察\nio.unobserve(element)\n\n// 关闭观察器\nio.disconnect()\n```\n\n### 使用 IntersectionObserver 优势\n\n使用前两种方式实现 lazyload 都需要监听浏览器 scroll 事件，而且要对每个目标元素执行 getBoundingClientRect() 方法以获取所需信息，这些代码都在主线程上运行，所以可能造成性能问题。\n\nIntersection Observer API 会注册一个回调方法，每当期望被监视的元素进入或者退出另外一个元素的时候(或者浏览器的视口)该回调方法将会被执行，或者两个元素的交集部分大小发生变化的时候回调方法也会被执行。通过这种方式，网站将不需要为了监听两个元素的交集变化而在主线程里面做任何操作，并且浏览器可以帮助我们优化和管理两个元素的交集变化。\n\n## 参考资料\n\n1. [原生 JS 实现最简单的图片懒加载](https://juejin.im/entry/599a78be6fb9a0247e424d67)\n2. [IntersectionObserver](https://github.com/justjavac/the-front-end-knowledge-you-may-dont-know/issues/10)\n3. [IntersectionObserver API 使用教程](http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html)\n4. [MDN-Intersection Observer API](https://developer.mozilla.org/zh-CN/docs/Web/API/Intersection_Observer_API#Browser_compatibility)\n\n\u003cbr\u003e\n\n\n---\n\n\u003e Website [lz5z.com](https://lz5z.com) \u0026nbsp;\u0026middot;\u0026nbsp;\n\u003e GitHub [@Leo555](https://github.com/Leo555) \u0026nbsp;\u0026middot;\u0026nbsp;\n\u003e demo [lazyload](https://lz5z.com/lazyload)\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleo555%2Flazyload","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fleo555%2Flazyload","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleo555%2Flazyload/lists"}