动态import

  • import函数的参数,指定所要加载的模块的位置。
  • import命令能够接受什么参数,import()函数就能接受什么参数,两者区别主要是后者为动态加载
  • import()返回一个 Promise 对象。
  • 它是运行时执行,也就是说,什么时候运行到这一句,就会加载指定的模块
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <button id="btn">按钮</button>
    <script type="text/javascript">
      document.getElementById("btn").onclick = function () {
        import("./a.js")
          .then(() => {
            console.log(111);
          })
          .catch(() => {
            console.log(222);
          });
      };
    </script>
  </body>
</html>
//a.js
console.log('a.js执行了~');
posted @ 2023-01-29 13:29  z_bky  阅读(82)  评论(0)    收藏  举报