PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 26, 2022

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

 November 26, 2022     asynchronous, html, javascript, module     No comments   

Issue

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


Solution

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



Answered By - M4trix Dev
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing