Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

promise实现图片异步加载

Sunny-117 opened this issue · comments

commented
promise实现图片异步加载
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    h1 {
      display: block;
    }
  </style>

  <body>
    <div id="box">
      <h1>我是一张缺省图</h1>
    </div>
  </body>
</html>
<style></style>
<script>
  var oBox = document.getElementById("box");
  var oH = document.querySelector("h1");

  function loadImageAsync(url) {
    return new Promise(function (resolve, reject) {
      var image = new Image();

      image.onload = function () {
        resolve(image);
      };

      image.onerror = function () {
        reject(new Error("Could not load image at " + url));
      };

      image.src = url;
    });
  }
  // 模拟一下异步加载图片
  // 用setTimeoutm模拟ajax调用接口,获取接口返回的图片路径,然后传入函数中,函数中已经提前创建好了
  // 图片标签。我们在.then的回调函数中自行决定插入div容器中做一些事,比如把缺省图隐藏掉
  setTimeout(() => {
    loadImageAsync(
      "https://img2020.cnblogs.com/blog/2221918/202104/2221918-20210429012928150-1671892053.png"
    ).then((res) => {
      oH.style.display = "none";
      oBox.appendChild(res);
    });
  }, 1000);
</script>

function loadImgAsync(url) { let img = new Image(url); return new Promise((rs, rj) => { img.onload = () => { rs(); } img.onerror = () => { rj(); } img.src = url; }) }