Skip to content

图片懒加载 #7

@twosugar

Description

@twosugar

大致思路是,给每个需要懒加载的图片一个属性lazy-img-src,属性值为真正需要渲染的图片,监听滚动,在滚动停止的时候,获取所有属性名为lazy-img-src的元素,判断元素是否出现在可视区域,若存在,使用lazy-img-src中的地址替代图片src中的地址,替代之后 删除lazy-img-src。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .box {
      height: 1400px;
    }
  </style>
</head>
<body>
  <div class="box">
    hello
  </div>

  <img class="img" lazy-img-src="https://img.alicdn.com/tfs/TB1rOrHVIbpK1RjSZFyXXX_qFXa-116-116.png" src="https://avatars1.githubusercontent.com/u/42201025?s=180&v=4">

</body>
<script>
  
  let timer = null
  window.onscroll = scroll;

  function scroll() {
    if (timer) {
      clearTimeout(timer) 
    }
    timer = setTimeout(() => {
      getList()
    }, 500)
  }

  function getList() {
    const nodes = document.querySelectorAll('[lazy-img-src]');
    if (!nodes || !nodes.length) {
      return;
    };
    const length = nodes.length;
    for (let i = 0; i < length; i++) {
      if (nodes[i].offsetParent == null) {
        return;
      }
      const scrollTop = document.documentElement.scrollTop
      const height = document.body.clientHeight
      if (window.innerHeight + scrollTop > nodes[i].offsetTop) {
        nodes[i].src = nodes[i].getAttribute('lazy-img-src')
        nodes[i].removeAttribute('lazy-img-src')
      }
    }
  }
</script>
</html>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions