0

I basically would like to run an async function as soon as an html page load. I have 2 js files (one module and a simple js) which are loaded however my code seems to not work consistently. Sometime I get an error saying that a function is not defined.

Here is my code

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 (module)

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

store.js (simple javascript)

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

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

Most of the time I am able to run readDatabase() but sometime I get an error - see below. enter image description here

Any idea on what is the problem and how to resolve this issue?

Many thanks!!

0

1 Answer 1

0

I solved by adding defer to the script. Defer makes the script to be triggered in the exact order of your code, so in this way I am sure that the readDatabase function is imported before the store.js script is executed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.