如何在加载网页时从模块 javascript 加载异步函数

How to load an async function from a module javascript when webpage load

我基本上想在 html 页面加载后立即 运行 一个异步函数。我加载了 2 个 js 文件(一个模块和一个简单的 js),但是我的代码似乎无法始终如一地工作。有时我收到一条错误消息,指出函数未定义。

这是我的代码

Page.html

<body>
  //...
  <script type="module"> import { function1 } from "../../js/app.js";
    window.function1 = function1; </script>
  <script type="module"> import { readDatabase } from "../../js/app.js";
    window.readDatabase = readDatabase; </script>
  <script src="../../js/store.js" async="async"></script>
</body>

app.js(模块)

export async function readDatabase() {
  // does something async
  return value;
}

store.js(简单javascript)

if (document.readyState == 'loading') {
  document.addEventListener('DOMContentLoaded', ready);
} else {
  ready();
}

function ready() {
  const value = readDatabase();
  // do some there stuff
}

大多数时候我能够 运行 readDatabase() 但有时我会遇到错误 - 见下文。

知道问题是什么以及如何解决这个问题吗?

非常感谢!!

我通过在脚本中添加 defer 来解决。 Defer 使脚本按照您的代码的确切顺序被触发,所以通过这种方式,我确信在执行 store.js 脚本之前导入了 readDatabase 函数