异步加载图片函数封装(使用Promise)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script>
    loadImageAsync("./loadImg.jpg").then(image => document.body.appendChild(image))

    // 异步加载图片函数封装
    function loadImageAsync(url) {
    
    
      return new Promise(function(resolve, reject) {
    
    
        const image = new Image();
        image.src = url;
        image.onload = function() {
    
    
          resolve(image);
        };
        image.onerror = function() {
    
    
          reject(new Error('Could not load image at ' + url));
        };
      });
    }
  </script>
</body>
</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_27575925/article/details/111827406