Home > Enterprise >  How to check if script done running
How to check if script done running

Time:09-26

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?

CodePudding user response:

I think as like this

  var IsRunning = false;
  function myFunction() {
   if (!IsRunning) {
    IsRunning = true;
    }
    }

CodePudding user response:

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()
};
  • Related