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

Time:01-26

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!!

CodePudding user response:

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

  •  Tags:  
  • Related