0

I have a Javascript file that has to be loaded in a body of HTML documents by my main.js file of code. there is a function in this Javascript file to be executed after this JS file has fully loaded. but the problem is that async-await doesn't wait for the js file to be fully loaded and it runs my function after await sentence sooner. my sample code :

-> main.js file :

   async main() {
    await Promise.all([
      bodyScript("assets/js/form.js"),
 
     ]);

     func_form_view(); // this function has to wait and not run untill the above js file become fully loaded.
  
  }


   bodyScript(scriptUrl) {
  
    return new Promise((resolve, reject) => {
      const scriptElement = document.createElement('script')
      scriptElement.src = scriptUrl
      scriptElement.onload = resolve
      document.body.appendChild(scriptElement)
    })
 
  }

-> form-2.js file :

function func_form_view() {
-- // code
-- // code
.
.
.
-- // code
  console.log('hi')
} 

and it's why I usually get this error: "func_form_view function has not defined".

but I think anything looks right!!!

Program_Lover
  • 91
  • 1
  • 10
  • 1
    Can you provide a [mcve]? – JSON Derulo Jun 16 '21 at 06:43
  • Do you have the "hi" logged? What says the Network panel of your dev tools? – Kaiido Jun 16 '21 at 06:48
  • func_form_view function has not defined its an error i encounter – Program_Lover Jun 16 '21 at 06:51
  • JSON Derulo, cant show more simple – Program_Lover Jun 16 '21 at 06:52
  • You are showing the code, but you are not showing us how it is integrated. Can you set up a stackblitz (or similar)? – JSON Derulo Jun 16 '21 at 07:25
  • Does this answer your question? [document.createElement("script") synchronously](https://stackoverflow.com/questions/3248384/document-createelementscript-synchronously) – ceving Jun 16 '21 at 08:00
  • @JSON Derulo, https://stackblitz.com/edit/js-lvm8kl?file=index.js – Program_Lover Jun 16 '21 at 08:11
  • @ceving thanks but as u can see im already using scriptElement.onload = resolve at bodyScript function, but it has problem yet. – Program_Lover Jun 16 '21 at 08:19
  • Now I see what's wrong. "A variable in the global scope should be accessible to all scripts loaded after it is declared" ([source](https://stackoverflow.com/questions/3244361/can-i-access-variables-from-another-file/3244411#3244411)). But you are trying to use the function before it is declared. – JSON Derulo Jun 16 '21 at 08:20
  • JSON Derulo, no i dont think so, my function is run before its js file load. i think the problem is that await dosent wait ! – Program_Lover Jun 16 '21 at 08:27
  • Omg, this works fine when I cleared the browser cache !!! , but still problem in stackblitz.com/edit/js-lvm8kl?file=index.js link, by the way my older cache had problem. sorry guys. and thanks. – Program_Lover Jun 16 '21 at 08:35

0 Answers0