-1

I'm injecting programmatically some text-code into script, and I need to run some code only after the script is done running.

My code:

const InjectScript = (scriptContent) => {
  const script = document.createElement("script");
  script.type = "text/javascript";
  script.text = scriptContent;
  document.head.appendChild(script);

 //run some code after script executed
   someCode()
};

How can I check if the script is done running?

Masksway
  • 205
  • 3
  • 11

2 Answers2

-1

I think as like this

  var IsRunning = false;
  function myFunction() {
   if (!IsRunning) {
    IsRunning = true;
    }
    }
  • This is either not needed (if the inserted JS is not async), or useless (if it is). Aside from the fact that it is making use of global variables (which is generally frowned upon). – connexo Sep 26 '21 at 12:58
-1

async await seems like the best choice if your runtime is okay with ECMAScript 2017 syntax, like so:

const InjectScript = async (scriptContent) => {
  const script = await document.createElement("script");
  script.type = await "text/javascript";
  script.text = await scriptContent;
  await document.head.appendChild(script);

  //run some code after script executed
  await someCode()
};
John Hugh
  • 11
  • 2